繁体   English   中英

如何遍历对象以在 EJS 上显示值

[英]How do I iterate through object in order to display the values on EJS

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

本地主机上显示什么

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

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

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

另外, 不要使用for..in来迭代数组

<tbody>
  <% for(let 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM