0

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

          });

        });   

    });
});

1 Answer 1

2

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++) {
      //...
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Robert never? It depends on the situation.. You should try to avoid iterating over the same array (or two arrays expected to be of similar length) in nested loops if you can, but obviously there are many times where that's something you have to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.