简体   繁体   中英

jquery, how to loop through complex array

I did an ajax and returned an multi-dimensional array that is 5 level deep and each level have many items. I want to loop through each level and create a HTML syntax. After all level 5 is done. I will join all the syntax and append the entire list into HTML.

right now I am concerned about how to loop it correct it.

the array structure is like below

var array = [object, object, object, object]
            |0 object level 1
              |1 object level 2
                |0 object level 3
                  |0 object level 4
                    |0 object level 5
            |1 object
            |2 object 
            |3 object 

here is a simplified sample data

var test = [
    {
        "someid":"25",
        "level1":[
            {
                "name":"john doe",
            }
            "level2": [
            {
                "order_quantity":"1",
                "order_price":"12.00",
                "level3":[
                {
                    "addon_price":"2.00"
                }]
            }]
        }]
    }
]

I try to use javascript for loop but after 2nd level it becomes very ugly and hard to track.

first level loop

for(i=0; i<array.length;i++)

second level loop

for(n=0; n<array[i].level1.length;n++)

Third level loop

for(y=0;y<array[i].level2[n].level3.length;y++) 

I dont think this is the right way.

What would be the right way to loop through an array like this

I also have jquery. but not sure how to use $.each to do this either.

so jquery solution is welcome.

You could use a recursive approach.

 var array = [[[1, 2, 3, 4], [[5, 6]]], [7, 8], [9, 10], [11, 12]]; array.forEach(function iter(a) { if (Array.isArray(a)) { a.forEach(iter); return; } console.log(a); }); 

Or use a hard coded solution

 var test = [{ someid: "25", level1: [{ name: "john doe", level2: [{ order_quantity: "1", order_price: "12.00", level3: [{ addon_price: "2.00" }] }] }] }]; test.forEach(function (a) { a.level1.forEach(function (b) { b.level2.forEach(function (c) { c.level3.forEach(function (d) { console.log(d.addon_price); }); }); }); }); 

Or use a more dynamic solution, if the sub levels follows the same building rule.

 var test = [{ someid: "25", level1: [{ name: "john doe", level2: [{ order_quantity: "1", order_price: "12.00", level3: [{ addon_price: "2.00" }] }] }] }]; test.forEach(function iter(level) { return function (a) { if (Array.isArray(a['level' + level])) { a['level' + level].forEach(iter(level + 1)); return; } Object.keys(a).forEach(function (k) { console.log(a[k]); }); } }(1)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM