简体   繁体   中英

Iterating over an array in Pug

I'm retrieving data from an external API in JSON format and sending that data to my view. The issue I'm having is, one of the properties within the Object is an Array of Objects. Following the Pug Documentation ( Pug Iteration ), I can successfully iterate over the Array like so:

block content
  .row
    each item in data.array
      .col-md-3
        .well
          img(src=`${item.media.m}`)
          h5 #{item.title}
          p by #{item.author}

However, the Array stores 20 values and ideally, I would like to iterate over four values at a time so I can achieve the following output:

<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>

EDIT:

JSON Structure

{
  "string": "string",
  "string": "string",
  "array": [
    {
      "string": "string",
      "media": {
        "m": "string"
      }
    },
    {
      "string": "string",
      "media": {
        "m": "string"
      }
    }
  ]
}  

You can first group items by 4 then use two nested loops to iterate over groups and over items in groups

- 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}

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