简体   繁体   English

如何以 3 个块迭代 JSON object?

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

So i have a json object that is being served by nodejs.所以我有一个由nodejs服务的json object。

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.我想在 3 行中制作文章,然后在文章下方的 3 行中制作 div(包含文章的信息。

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).我遇到了问题,因为我不确定如何加入迭代 object 的 for 循环(一次只有 3 个)。

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.使用递增 3 而不是 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.模数 (%) function 的工作原理是将“i”除以 % 符号后的数字。 If the remainder is 0 (so exactly dividable by 3), it will be true and execute the code.如果余数为 0(可以被 3 整除),则为真并执行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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