Problem with EJS template

Hi all,

I’m trying to loop over an objects array inside an EJS template. This objects array is coming from the backend.
I’ve created a table in EJS, and I’m trying to loop over the objects array and insert its individual elements as the table rows, but for some reason, this is not working.

Here’s a piece of the code:

<table style="width:100%">
      <tr>
        <th>Rank</th>
        <th>UserId</th>
        <th>Score</th>
      </tr>
      <% for(let i=1; i < rankedProfitArray.length + 1; i++) {%>
        <tr>
          <td><%= i %></td>
          <td><%= rankedProfitArray[i].userId%></td>
          <td><%= rankedProfitArray[i].score%></td>      
        </tr>
      <% } %>
    </table>

I’ve tried looping over the array outside of a table, testing with ‘p’ tags, and everything is working fine. But doesn’t seem to be working inside of a table.

Please help.

Hello @csibanda17.
When you say looping over the array outside of a table, testing with p tags, and everything is working fine, do you mean inside ejs? From your code I am seeing you iterating up to rankedProfitArray.length + 1 . How then do you expect rankedProfitArray[i].userId not to throw? Essentially there are no elements with indices rankedProfitArray.length and rankedProfitArray.length + 1.

1 Like

Hi @nibble,
Thanks for pointing out my error with rankedProfitArray.length + 1
Everything is working well now.

Many thanks

1 Like