CLIX159 CLIX159 - 4 months ago 8
JSON Question

Parsing nested array objects in json using Java script/jQuery

I have a JSON file like this:

var a = [
{"name":"avc"},
{"name":"Anna"},
{"name":"Peter"},
{"Folder":[
{"name":"John"},
{"name":"Anna"},
{"Folder":[
{"name":"gg"},
{"name":"hh"}
]
}
]
}
];


It can be nested to any number of levels.
I want to traverse this file for any number of levels.
How can I achieve this using Javascript/JQuery

Thanks

Answer

I read your question like this:

How can I iterate through an array of object, where an object may have children of it's own. And every child may have children and so on...

One way is to write a recursive function, which is a function that calls itself. Here's a recursive function which will log every post into console. Note that I've changed your model into a proper object. Also, I've added name to folder, but that can be removed if not necessary.

var a = [
    {name:"avc"},
    {name:"Anna"},
    {name:"Peter"},
    {name:"Folder name1",
     folder:[
           {name:"John"},
           {name:"Anna"},
   {name: "Folder name2",
    folder:[ 
          {name:"James"},
          {name:"Clark"},
          {name: "Folder name3",
           folder:[
             {name:"Cecilia"},
             {name:"Clara"}
           ]},
          {name:"Stephen"}
        ]
    }
  ]
 }
];



function read(obj){
    for(var i = 0; i < obj.length; i++)
    {
        console.log(obj[i].name); // Or do what you need here...
        if(obj[i].folder)
        {
          // Recursive call
          read(obj[i].folder);
        }
    }
}

read(a);

Comments