I've been trying to figure this out for quite some time now. I'm to a point where I'm having dreams about it. So, my input is:-
var obj = {
"one": {
"propOne": 1,
"propTwo" : {
"innerProp" : "hello"
},
"two": {
"twoProp": "something",
"twoProp2": {
"inside": "world",
"deep": {
"end": "ok"
}
}
}
}
Pretty standard object. What I'm trying to do is traverse and get the key with property if property's value is an object. So, my output would be something like this:-
one
one.propTwo
one.propTwo.innerProp
two
two.twoProp2
two.twoProp2.deep
two.twoProp2.deep.end
So far I've been able to get all the properties whose value is object but what I'm struggling on is trying to get the exact structure as shown on the output above.
I have this so far:-
function isObject(obj) {
'use strict';
var result = false;
if (typeof obj === 'object' && obj !== null && Object.keys(obj).length > 0) {
result = true;
}
return result;
}
function recurse(obj, key) {
'use strict';
key = key || '';
if (isObject(obj)) {
for (var k in obj) {
if (isObject(obj[k])) {
var dot = key ? '.' : '';
key += key ? '.' + recurse(obj[k], k) : recurse(obj[k], k);
} else {
}
}
}
return key + ',';
}
If you run the code above it's quite clear the output is far from what I want but it does get all the necessary properties which is needed to be displayed. I'm just stomped on trying to get it display exactly like I want it. Any pointer would be appreciated. It doesn't have to be recursive. I just thought it was easier to achieve this with recursion.
Fiddle here
@Tomalak is right that this is a duplicate of the linked post but I'm posting a generic solution rather than the one posted in the original post.
var stack = [];
function saveStack(arr) {
stack.push(arr);
}
function recurse(obj, key) {
'use strict';
key = key || '';
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
if (isObject(obj[k])) {
var dot = key ? '.' : '';
var stack = key + dot + k;
saveStack(stack);
recurse(obj[k], stack);
}
}
}
}