Loop through JSON in EJS

前端 未结 3 793
旧时难觅i
旧时难觅i 2020-12-02 22:12

I have codes in EJS below,


<% for(var i=0; i

        
相关标签:
3条回答
  • 2020-12-02 22:46

    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

    0 讨论(0)
  • 2020-12-02 22:56

    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%>
    <%} %>
    
    0 讨论(0)
  • 2020-12-02 22:58

    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>
    
    0 讨论(0)
提交回复
热议问题