Wim
Wim

Reputation: 213

running a for each loop for nested json

this is what my variable looks like in the debugger

Ok so essentially i have what i think is a JSON object. You see its properties in the picture i provided, now pretty much what i have been trying to do is to write a for each for a particular lvl.

$.each(toSort.items.items.items.items.items, function (index, value) {
    console.log(index);
});

So pretty much what i want is a loop nested in the 5th layer, run code. so what i want to know is why is the code above invalid?

Upvotes: 2

Views: 1471

Answers (2)

duatis
duatis

Reputation: 184


Items are arrays in every layer before 5th as well, so to access the items array inside the first layer you need to specify an index, by doing toSort.items.items, the second items is beign accessed as a property, that doesn't exist, to access the second items array inside the first items array you must access it as toSort.items[0].items and so on.

An example of subsequent access might be

toSort.items[0].items[0].items[0].items[0].items[0]
toSort.items[0].items[0].items[0].items[0].items[1]
toSort.items[0].items[0].items[0].items[0].items[2]
...
toSort.items[0].items[0].items[0].items[1].items[0]
toSort.items[0].items[0].items[0].items[1].items[1]
toSort.items[0].items[0].items[0].items[1].items[2]
...
...
...
toSort.items[1].items[1].items[1].items[1].items[0]
toSort.items[1].items[1].items[1].items[1].items[1]
toSort.items[1].items[1].items[1].items[1].items[2]

Looks like it can be used a bit of recursion, isn't it?

Upvotes: 1

oshell
oshell

Reputation: 9103

Because items is always an array you would have to refer to a certain index within this array. If you want to get one single item you must use the indexes, too.

toSort[0].items[0].items[0] //third level

If you want all values from that arrays you are better off using more than one loop. Moreover for() is much faster than jQuery's each().

for(var i = 0; i < toSort i++){
    //first level
    for(var j=0; j < toSort[i].items; j++){
        //second level
        for(var x=0; x < toSort[i].items[j].items; x++){
           //third level
        }
    }
}

Upvotes: 2

Related Questions