在NodeJS中循环嵌套的Json数据

时间:2018-04-05 18:51:00

标签: javascript json node.js ejs

在我的模拟数据中,我能够循环访问大部分数据。 当你到达即将到来的学生时,你可以看到我嵌套了一些数据。 我遇到的问题是能够打印嵌套数据。

{
  "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>
    <% }) %>

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

1 个答案:

答案 0 :(得分:2)

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

学生数组位于您在ejs模板的第一行中循环的数组中