Loop through JSON in EJS

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

I have codes in EJS below,


<% for(var i=0; i

        
3条回答
  •  旧时难觅i
    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
    

    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:

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

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

    1 bob
    2 john
    3 jake

提交回复
热议问题