Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

each within each within each

I'm new working with JSON and the getJSON function etc and I'm trying to get data from a JSON that goes down several levels and can have multiple children. At the minute I can see the values I want by using .each with another .each such as:

$.each(data, function(i, value1) {
    $.each(value1, function(i, value2) {
        $.each(value2, function(i, value3) {
            $.each(value3, function(i, value4) {
                $.each(value4, function(i, value5) {
                    $.each(value5, function(i, value6) {
                        alert ("we got "+i);
                    });

The only problem is, I won't always know what is in the JSON and it could have unlimited children. So how would I go about making it dynamic as such?

Basically what I'm looking for is something to keep checking for children until it gets to the lowest level.

Also, I know the value i at the very end is the index for whatever value is in the JSON,

Is there any way to automate this also so that I could check for say, 'name' in the JSON and it would return the value of 'name'?

Here is a sample of the JSON i'm trying to work with:

[
 {
   "children": [
    {
      "children": [
       {
        "children": [
          {
            "children": [
              {
                "bucketPath": "AUDIO\\audio0.mp3",
                "id": 305,
                "modified": "2012-08-02T10:06:52",
                "name": "audio0.mp3",
                "state": "closed"
              }
like image 805
RoverK Avatar asked Aug 07 '26 21:08

RoverK


2 Answers

Use recursion:

function recurse(name, obj) {
    if (!obj || typeof obj != "object")
        alert("found leaf '"+name+"': "+obj);
    else
        $.each(obj, recurse);
}
recurse("root", data);

EDIT: Based on your JSON, one could make it more specific:

function recurse(arr) {
   for (var i=0; i<arr.length; i++)
       for (var prop in arr[i])
           if (prop == "children") // && arr[i].children instanceof Array
               recurse(arr[i].children);
           else
               alert("we got "+prop+": "+arr[i][prop]);
}
recurse(data);
like image 152
Bergi Avatar answered Aug 10 '26 11:08

Bergi


This sounds like it needs JPath or JSONPath

var name = jpath(data, '//name');
like image 34
Alnitak Avatar answered Aug 10 '26 11:08

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!