javascript - 在 Pug 中迭代数组

标签 javascript node.js express pug

我正在从外部 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/

相关文章:

javascript - 如何在 map 上添加鼠标悬停表单

javascript - Angular JS 获取出现在输入文本中的值

mysql - VALID 查询上的 Nodejs MySQL ER_PARSE_ERROR

node.js - 关注者的实时新闻源 - 哪些工具和语言?

node.js - 如何从 POST 正文获取 wav 文件并使用 Node JS/Express 上传

node.js - 错误 : ENOENT: no such file or directory index. html Node.js

javascript - 使用 Sequelize 为多对多关系创建新实例

javascript - 让 $.post 函数返回父函数中的响应

javascript - 哪个是在链接上调用 javascript 函数的最佳方式

database - 环回: Cannot find module 'negotiator'