0

I have a deeply nested object: { a: { b: { c: 3 }, d: 4 } }.

How to get all namespaces within this object?

So, I need to get: ['a.b.c', 'a.d'].

2
  • 3
    d is not inside a! Commented May 19, 2017 at 9:29
  • Recursive Object.keys() If a key is an object, get its keys as well. Commented May 19, 2017 at 9:32

4 Answers 4

4

You can create recursive function using for...in loop.

var obj = {a: {b: {c: 3} }, d: 4 }

function getKeys(data, prev) {
  var result = []
  for (var i in data) {
    var dot = prev.length ? '.' : '';
    if (typeof data[i] == 'object') result.push(...getKeys(data[i], prev + dot + i))
    else result.push(prev + dot + i)
  }
  return result;
}

console.log(getKeys(obj, ''))

Instead of for...in loop you can use Object.keys() and reduce().

var obj = {a: {b: {c: 3} }, d: 4 }

function getKeys(data, prev) {
  return Object.keys(data).reduce(function(r, e) {
    var dot = prev.length ? '.' : '';
    if (typeof data[e] == 'object') r.push(...getKeys(data[e], prev + dot + e))
    else r.push(prev + dot + e)
    return r;
  }, [])
}

console.log(getKeys(obj, ''))

Sign up to request clarification or add additional context in comments.

2 Comments

If you use var obj = {abc:1, d: 1} with your function, you get the same result...
@Gerardo Furtado I forgot about dots, i think it work fine now.
3

var t = {a: {b: {c: 3} }, d: 4 };

path (t, '');

function path(t, sofar) {

  if (Object.keys(t).length === 0)
    console.log(sofar.substr(1));
  
  var keys = Object.keys(t);
  
  for (var i = 0 ; i < keys.length ; ++i) {
    path(t[keys[i]], sofar+'.'+keys[i]);
  }
  
}

Comments

1

You could create a script in order to flatten the object and return the keys. You could also think to convert it to an array and use the default flatten of arrays. Here an example of flattening the object.

var flattenObject = function(ob) {
    	var toReturn = {};
    	
    	for (var i in ob) {
    		if (!ob.hasOwnProperty(i)) continue;
    		
    		if ((typeof ob[i]) == 'object') {
    			var flatObject = flattenObject(ob[i]);
    			for (var x in flatObject) {
    				if (!flatObject.hasOwnProperty(x)) continue;
    				
    				toReturn[i + '.' + x] = flatObject[x];
    			}
    		} else {
    			toReturn[i] = ob[i];
    		}
    	}
    	return toReturn;
    };

    var obj = {a: {b: {c: 3} }, d: 4 }
    console.log(Object.keys(flattenObject(obj))); // ['a.b.c', 'd']

p.s. your object in the question has a mistake, or what you want is not what you are asking. d is at the same level of a, so you can't achieve "a.d", but "d"

6 Comments

It's Object.keys, lowercase k. Besides that, it doesn't log what you show in your answer. Convert this into a snippet, it's easier to check.
Hi @GerardoFurtado, thanks for the reply, changed it, I tried it in the console and it prints what I described...could you please tell me how to convert it to a snippet? sorry for the "newbie" question but I am new to stackoverflow
Now it's correct. If you edit your answer, you'll gona see a icon like this: <> . It's the seventh from left. Click it, you can put your code in the JavaScript box.
@GerardoFurtado thanks this is awesome! Everytime I was using jsfiddle to provide snippets but this is so much easier! thanks again :)
awesome ^_^ thanks again! you won't see anymore an answer by me without a code snippet :D Have a great day!
|
0

You could check the keys and iterate otherwise push the path to the result set.

function getKeys(object) {
    function iter(o, p) {
        var keys = Object.keys(o);
        keys.length ?
            keys.forEach(function (k) { iter(o[k], p.concat(k)); }):
            result.push(p.join('.'));
    }
    var result = [];
    iter(object, []);
    return result;
}

var object = { a: { b: { c: 3 } }, d: 4 };

console.log(getKeys(object));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.