-1

I have a problem with iterating objects on EJS. I am connected to a DB on the backend, and I can console log the objects but when I run it through the front end, I get a result of [Object]

Here is the code on my code in the backend

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)
        }
    });
});

And on 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>

What is displaying on localhost

hoangdv
  • 15,138
  • 4
  • 27
  • 48
noobdev123
  • 51
  • 7

1 Answers1

0

Instead of calling res.render() in each loop iteration, build an array of data and pass that only once

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

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

Also, 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>
Phil
  • 157,677
  • 23
  • 242
  • 245