【问题标题】:How do I iterate through object in order to display the values on EJS如何遍历对象以在 EJS 上显示值
【发布时间】:2021-12-23 10:51:08
【问题描述】:

我在 EJS 上迭代对象时遇到问题。我连接到后端的数据库,我可以控制台记录对象,但是当我通过前端运行它时,我得到 [Object] 的结果

这是我后端代码中的代码

app.get('/usageData', (req, res) => {

    tableSvc.queryEntities('usageData', query, null, function (error, result, response) {
        if (!error) {

            Object.keys(result).forEach(function(key){
                const final=result[key]
                res.render("usage",{final})
            })
        } else {
            console.log(error)
        }
    });
});

在 EJS 上:

<ul>
  <table >        
      <table class="table table-hover">
          <thead>
            <tr class="indexs">
              <th scope="col">PartitionKey</th>
              <th scope="col">RowKey</th>
              <th scope="col">Action</th>
              <th scope="col">SelectedReports</th>
              <th scope="col">reportInterval</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <% for(var i in final) { %>  
                <tr style="font-size: 15px">
                  <td><%= final[i].PartitionKey %>&ensp;</td>
                  <td><%= final[i].RowKey %>&ensp;</td>
                  <td><%= final[i].Action %>&ensp;</td>
                  <td><%= final[i].SelectedReports %>&ensp;</td>
                  <td><%= final[i].reportInterval %>&ensp;</td>
                 </tr>
              <% } %>

            </tr>
          </tbody>
        </table>
  </table>
</ul>

【问题讨论】:

  • 不要在forEach中调用render函数

标签: javascript node.js express ejs


【解决方案1】:

不要在每次循环迭代中调用res.render(),而是构建一个数据数组并只传递一次

if (error) {
  console.error(error)
  return res.status(500).send(error)
}

res.render("usage", {
  final: Object.values(result)
})

另外,don't use for..in to iterate arrays

<tbody>
  <% for(const usage of final) { %>
    <tr style="font-size: 15px">
      <td><%= usage.PartitionKey %>&ensp;</td>
      <td><%= usage.RowKey %>&ensp;</td>
      <td><%= usage.Action %>&ensp;</td>
      <td><%= usage.SelectedReports %>&ensp;</td>
      <td><%= usage.reportInterval %>&ensp;</td>
    </tr>
  <% } %>
</tbody>

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 2022-06-29
    • 2019-06-04
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多