-2

I have a JSON file like this:

{[
    {"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

7
  • 3
    Your question needs more details. What exactly do you want to do? Commented Jul 26, 2016 at 10:28
  • 2
    That's not a JSON fille. You must remove the variable assignment to get a JSON file. Commented Jul 26, 2016 at 10:28
  • Using statements and expressions to traverse it might work. Commented Jul 26, 2016 at 10:29
  • 2
    have you heard of a recursive function ? Commented Jul 26, 2016 at 10:30
  • 1
    look here stackoverflow.com/questions/6890969/… or here stackoverflow.com/questions/2098276/… Commented Jul 26, 2016 at 10:30

2 Answers 2

2

You could iterate with Array#forEach and if a Folder is an array, then iterate that, too.

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

a.forEach(function iter(a) {
    if (Array.isArray(a.Folder)) {
        a.Folder.forEach(iter);
        return;
    }
    console.log(a.name);
});

Sign up to request clarification or add additional context in comments.

Comments

1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.