You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在EJS中遍历对象以正常显示数据库查询返回的属性值

问题原因

后端代码问题

  • Azure Table Storage的queryEntities接口返回的有效业务数据存放在result.entries属性中,你直接遍历result的所有键,拿到的不是目标实体列表
  • 不能在循环中反复调用res.render,该方法每个请求只能执行一次,循环调用会导致响应逻辑异常,传递给模板的数据结构不符合预期

模板代码问题

  • 存在多余的嵌套<table>标签和空<tr>标签,HTML结构错误会干扰渲染逻辑
  • 若Azure返回的字段为类型包装对象,直接读取字段名会拿到对象本身而非实际值,就会显示[Object]

修复代码

后端修复

app.get('/usageData', (req, res) => {
    tableSvc.queryEntities('usageData', query, null, function (error, result, response) {
        if (!error) {
            // 直接取实体列表传递给模板,仅调用一次render
            const final = result.entries
            res.render("usage", {final})
        } else {
            console.log(error)
        }
    });
});

EJS模板修复

<ul>
  <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>
          <% for(var i in final) { %>  
            <tr style="font-size: 15px">
              <!-- 若仍显示[Object],就改为final[i].PartitionKey._ 以此类推其他字段 -->
              <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>
          <% } %>
      </tbody>
    </table>
</ul>

内容的提问来源于stack exchange,提问作者noobdev123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:48:05