【问题标题】:Looping nested Json data in NodeJS在 NodeJS 中循环嵌套的 Json 数据
【发布时间】:2018-09-15 16:42:46
【问题描述】:

在我的模拟数据中,大部分情况下我都能够遍历一些数据。 当你看到即将到来的学生时,你可以看到我嵌套了一些数据。 我遇到的问题是能够打印嵌套数据。

{
  "upcoming": [{
    "id": 1,
    "date": "Feb 2nd, 2018",
    "time": "2 to 4pm",
    "status":"$45",
    "course": "Oil Painting",
    "course_type": "(Individual)",
    "student":[
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      }
    ]
  },{
    "id": 2,
    "date": "Feb 2nd, 2018",
    "time": "2 to 4pm",
    "status":"$45",
    "course": "Oil Painting",
    "course_type": "(Group)",
    "student":[
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      },
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      },
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      }
    ]
  },{
    "id": 2,
    "date": "Feb 2nd, 2018",
    "time": "2 to 4pm",
    "status":"$45",
    "course": "Oil Painting",
    "course_type": "(Group)",
    "student":[
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      },
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      },
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      }
    ]
  }],
  "future":[{
    "id": 1,
    "date": "Feb 2nd, 2018",
    "time": "2 to 4pm",
    "status":"$45",
    "course": "Oil Painting",
    "course_type": "(Group)",
    "student":[
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      },
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      },
      {
        "name": "Ann Perkins",
        "image": "/img/student-icon.png"
      }
    ]
  }]
}

我可以将日期、状态和课程打印到我的 ejs 模板中,但是当我尝试显示学生图像时,我收到一条错误消息,提示它未定义。

<% data.upcoming.forEach((record) => { %>
    <tr>
      <td><%=record.date%>
          <span style="display: block;font-size:10pt;">3 to 4pm</span>
      </td>
      <td>Recieved
        <span style="display:block; font-size: 16pt; color:#7c0000;"><%=record.status%></span>
      </td>
      <td><%=record.course%>
        <span style="display:block;font-size:10pt;"><%=record.course_type%></span>
      </td>
      <td>
        LOOK HERE
        <% data.upcoming.student.forEach((person) => { %>
          <img rel="tooltip" data-placement="top" title="Ann Perkins" src="<%=person.image%>">
        <% }) %>
      </td>
    <% }) %>

我是否使用正确的方法来获取学生中的对象数组?

【问题讨论】:

    标签: javascript json node.js ejs


    【解决方案1】:

    您需要将data.upcoming.student.forEach((person) =&gt; { 替换为record.student.forEach(...)

    student 数组位于 ejs 模板第一行中您在上面循环的数组中

    【讨论】:

    • 感谢您的关注。我什么都没看到
    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多