[node.js] Loop through JSON in EJS

I have codes in EJS below,

<script>
    var row =<%-JSON.stringify(data)%>
    console.log(row);
</script>
<% for(var i=0; i<JSON.stringify(data).length; i++) {%>
   <tr>
     <td>
       <%= JSON.stringify(data)[i].id%>
     </td>
   </tr>
<% } %>

output of row is correct, an array of 3 objects, each with properties id, name etc.. I can manipulate the row to popuate the table in JS. However, I am wonderring whether there is a way to allow it be done in the above manner?

When I run the code above, JSON.stringify(data).length is not 3, but rather the length of the whole string.

Another questions is when I try to add

<% alert('t'); %> or <% window.alert('t'); %>, it gives me 'not defined' error...

Helps appreciated.

Regards Hammer

This question is related to node.js ejs

The answer is


JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296


in my case, datas is an objects of Array for more information please Click Here

<% for(let [index,data] of datas.entries() || []){  %>
 Index : <%=index%>
 Data : <%=data%>
<%} %>