Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to array of objects in template ejs?

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>
like image 240
nehas Avatar asked Mar 22 '15 04:03

nehas


2 Answers

<ul>
    <% for(var i=0; i<results.length; i++) { %>
        <li>
            <%= results[i] %>
        </li>
    <% } %>
</ul>
like image 57
Araoz Avatar answered Sep 27 '22 19:09

Araoz


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>
like image 37
James KR Avatar answered Sep 27 '22 19:09

James KR