JQuery and iteration on JSON objects

I'm currently trying to figure out how I can iterate over all objects in a JSON response. My object can have infinite helper objects, and they can also have infinite helper objects.

{
  "obj1" : {
      "obj1.1" : "test",
      "obj1.2" : {
         "obj1.1.1" : true,
         "obj1.1.2" : "test2",
         "obj1.1.3" : {
             ... // etc
         }
      }
  }
}

I'm just wondering if there is a script out of the box that can handle such objects?

+5
source share
5 answers

Here's a small function that tracks the depth of your tree walk, with stops along the way that allow you to perform an action (you did not specify what you really 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 ) );

, obj JSON, , - ( ):

depth: 0: obj1
depth: 1: obj1.1
 => test
depth: 1: obj1.2
// etc.
+4

, , - JSON, JavaScript Object Literal. , , - , JavaScript .

JS Object Literal, for. .

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' } });
+2

, JSON Object, ( ), .

JOrder, , , , . , .

https://github.com/danstocker/jorder

+1

jQuery JavaScirpt :

var jsonObject = $.parseJSON('{
  "obj1" : {
      "obj1.1" : "test",
      "obj1.2" : {
         "obj1.1.1" : true,
         "obj1.1.2" : "test2",
         "obj1.1.3" : {
             ... // etc
         }
      }
  }
}');

alert(jsonObject['obj1']);

parseJSON() JSON ( , JSON) JavaScript. , , JavaScript.

0

, de json. , node , . , .

, , jQuery. .

function recorrer(json) {

 $.each(json, function(index, value) {


         switch ($.type(value)){

             case 'string':
                  console.log(value) //for example                     
                 break;

             case 'object':
                 recorrer(value); // recursiva                     
                break;
         }



 });

};

0

All Articles