Robert
Robert

Reputation: 816

Nesting jQuery each() + json

Right now I have a json file that im using to populate data within a site.

LVL 1 - Main Collection page ->

LVL 2 - Collection Detail page ->

LVL 3 - Collection Detail page slider

So I have 3 $.each() statements nested within each other to achieve this. Everything works fine. I was just wondering if there is a more beneficial way of doing this?

example code:

$j.getJSON('collections.json', function(data, status){
    // lvl 1
    $.each(data.collections, function(i, collection){

     // do your thing

       // lvl 2
        $.each(collection.details, function(v, detail){

          // slider time - lvl 3

          $.each(detail.slider, function(s, slide){

            // inception achieved

          });

        });   

    });
});

Upvotes: 0

Views: 338

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

Not really .. this is pretty normal tree iteration. You may be able to cut some overhead if you just use ordinary for loops instead of $.each:

for (var i = 0; i < data.collections.length; i++) {
   var collection = data.collections[i];
   //do your thing
   for (var v = 0; v < collection.details.length; v++) {
      //...
   }
}

Upvotes: 2

Related Questions