[英]Iterating over an array in Pug
我正在以JSON格式从外部API检索数据,并将该数据发送到我的视图。 我遇到的问题是,对象中的属性之一是对象数组。 遵循Pug文档( Pug迭代 ),我可以像这样成功地遍历Array:
block content
.row
each item in data.array
.col-md-3
.well
img(src=`${item.media.m}`)
h5 #{item.title}
p by #{item.author}
但是,该数组存储20个值,理想情况下,我希望一次迭代四个值,以便获得以下输出:
<div class="row">
<div class="col-md-3">
<div class="well">
<img src="https://localhost/frank_the_pug.jpg">
<h5>Frank the Pug</h5>
<p>by MIB</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="well">
<img src="https://localhost/frank_the_pug2.jpg">
<h5>Frank the Pug 2</h5>
<p>by MIB</p>
</div>
</div>
</div>
编辑:
JSON结构
{
"string": "string",
"string": "string",
"array": [
{
"string": "string",
"media": {
"m": "string"
}
},
{
"string": "string",
"media": {
"m": "string"
}
}
]
}
您可以先按4对项目进行分组,然后使用两个嵌套循环在组和组中的项目之间进行迭代
- const groupBy4 = arr => arr.reduce((acc, item) => {
- let last = acc[acc.length - 1]
- if(last.length === 4) {
- acc.push(last = []);
- }
- last.push(item)
- return acc;
- }, [[]])
each group in groupBy4(items)
.row
each item in group
.col-md-3
.well
img(src=item.media.m)
h5 #{item.title}
p by #{item.author}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.