简体   繁体   中英

How to iterate over a JSON object in chunks of 3?

So i have a json object that is being served by nodejs.

I'm wanting to make articles in rows of 3, then div's in rows of 3 below the articles (that contain the information for the articles.

for (var infoset in jsonObj){
    createArtRow(jsonObj[infoset][info]);

    createDivRow(jsonObj[infoset][info]);
    
    // creates an article, then a div one at a time
}

I'm having issues, because i'm unsure how to join the for loop iterating over the object (only 3 at a time).

for (var infoset in jsonObj){
    for (var i = 0; i < 3; i ++) {
        createArtRow(jsonObj[infoset][info]);
    }
    for (var i = 0; i < 3; i ++){
        createDivRow(jsonObj[infoset][info]);
    }     
}
// ideally creates 3 articles, then 3 divs at a time.

I hope that makes sense.

Use a loop that increments by 3 instead of 1.

for (var i = 0; i < jsonObj.length; i += 3) {
    // here you can use jsonObj[i], jsonObj[i+1], and jsonObj[i+2] to create a row
}

You could use modulus funcion, which i think is a cleaner more readable approach:

let i =0
for (var infoset in jsonObj){ 
  If (i % 3 == 0 ){
   createArtRow(jsonObj[infoset][info]); 
  }
   createDivRow(jsonObj[infoset][info]); 
   i++;
}

Modulus (%) function works by deviding 'i' by the number after the % sign. If the remainder is 0 (so exactly dividable by 3), it will be true and execute the code.

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