How to parse (infinite) nested object notation?
Posted
by
kyogron
on Stack Overflow
See other posts from Stack Overflow
or by kyogron
Published on 2012-12-01T17:01:17Z
Indexed on
2012/12/01
17:03 UTC
Read the original article
Hit count: 221
I am currently breaking my head about transforming this object hash:
"food": {
"healthy": {
"fruits": ['apples', 'bananas', 'oranges'],
"vegetables": ['salad', 'onions']
},
"unhealthy": {
"fastFood": ['burgers', 'chicken', 'pizza']
}
}
to something like this:
food:healthy:fruits:apples
food:healthy:fruits:bananas
food:healthy:fruits:oranges
food:healthy:vegetables:salad
food:healthy:vegetables:onions
food:unhealthy:fastFood:burgers
food:unhealthy:fastFood:chicken
food:unhealthy:fastFood:pizza
In theory it actually is just looping through the object while keeping track of the path and the end result.
Unfortunately I do not know how I could loop down till I have done all nested.
var path;
var pointer;
function loop(obj) {
for (var propertyName in obj) {
path = propertyName;
pointer = obj[propertyName];
if (pointer typeof === 'object') {
loop(pointer);
} else {
break;
}
}
};
function parse(object) {
var collection = [];
};
There are two issues which play each out:
- If I use recurse programming it looses the state of the properties which are already parsed.
- If I do not use it I cannot parse infinite.
Is there some idea how to handle this?
Regards
© Stack Overflow or respective owner