我正在从外部 API 以 JSON 格式检索数据并将该数据发送到我的 View 。我遇到的问题是,对象中的属性之一是对象数组。按照 Pug 文档 ( Pug Iteration ),我可以成功地迭代数组,如下所示:
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}
关于javascript - 在 Pug 中迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934716/