How to array of objects in template ejs?

℡╲_俬逩灬. 提交于 2019-12-24 03:36:15

问题


I have a results variable that is an array of objects. I carry the results variable from my javascript file to my main route file. I am trying to render my page to display lists of each object in my template ejs file. I am able to list everything fine, but the lists are coming out as [object object] instead of the actual words that are in the objects. How do I get this to display as strings in my template file?

This is my route file:

app.get('/announcement', function(req,res){
        var getAnnouncements = require('../public/javascripts/announcement.js'); //Load the module, get the name of the script file

        //define the functions here
        var onSpreadsheetSuccess = function (results) { //result is announcementArray

            //add results list to template);
            res.render('announcement', {title: "Announcement page", results: results});

        }

        getAnnouncements.loadSheet(onSpreadsheetError, onSpreadsheetSuccess); //call the function from script with the parameters passed

})

This is what I am doing in my template ejs file:

<ul>
    <% results.forEach(function(result){ %>
        <li><%= result %></li>
    <%  }); %>
</ul>

回答1:


My answer is as follows. I changed one line from the answer by other person.

<ul>
<%for (var result in results){%>
  <li><%=result%>:<%=results[result]%></li>    
  <%}%>
</ul>



回答2:


This will show list of id of your results, just change _id by your property of objects as you want to show.

 <ul> 
  <% results.map((result)=>{%>
    <li><%= result._id %></li>
  <%}) %>
 </ul>



回答3:


<ul>
    <% for(var i=0; i<results.length; i++) { %>
        <li>
            <%= results[i] %>
        </li>
    <% } %>
</ul>



回答4:


Try this:

<ul>
     <%for (var result in results){%>
                <li><%=result%></li>    
        <%}%>
</ul>


来源:https://stackoverflow.com/questions/29190925/how-to-array-of-objects-in-template-ejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!