I'm currently trying to figure out how can I iterate over all of the objects in an JSON response. My object may have endless sub objects and they may also have endless sub objects.
{
"obj1" : {
"obj1.1" : "test",
"obj1.2" : {
"obj1.1.1" : true,
"obj1.1.2" : "test2",
"obj1.1.3" : {
... // etc
}
}
}
}
I was just wondering if there is a out of the box script that can handle such kind of objects?
Here's a little function that tracks the depth of your walk through the tree, with stops along the way to allow you to do perform an action (you didn't specify what you actually want to do, or when):
function dig( blob, depth ) {
var depth = depth || 0; // start at level zero
for( var item in blob ) {
console.log( 'depth: ' + depth + ': ' + item); // do something real here
if( typeof blob[item] === 'object' ) {
dig( blob[item], ++depth ); // descend
} else { // simple value, leaf
console.log( ' => ' + blob[item] ); // do something real here
}
}
}
console.log( dig( obj ) );
Assuming obj
is your JSON as above, this should give you something like (not tested):
depth: 0: obj1
depth: 1: obj1.1
=> test
depth: 1: obj1.2
// etc.
What you've represented in your question is not JSON, it's a JavaScript Object Literal. The difference is one is a string, and one is an actual literal object that can be used in JavaScript without further conversion.
To walk a JS Object Literal, use a simple recursive for loop. You don't need a separate library for that.
var walk = function(o){
for(var prop in o){
if(o.hasOwnProperty(prop)){
var val = o[prop];
console.log('Value = ',val, ', Prop =', prop, ', Owner=',o);
if(typeof val == 'object'){
walk(val);
}
}
}
};
walk({ 'foo':'bar', biz: { x: 'y' } });
Once you've parsed the JSON into an Object, You'll need to implement a tree-walker (a recursive function) to find particular values you are interested in.
However, JOrder will probably help you a great deal, it provides data management facilities, this saves you writing a tree-walker. and does a good, performant search and sort.
https://github.com/danstocker/jorder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With