nehas
nehas

Reputation: 247

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>

Upvotes: 9

Views: 35851

Answers (6)

VebDav
VebDav

Reputation: 162

You should be fine with this:

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

or when you rather like to use the forEach:

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

the object you push(ed) into your array:

const result = {
 title: anyTitle,
 input: anyInput
}

Upvotes: 1

exp
exp

Reputation: 510

With modern JS it can be simplified to

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

Upvotes: 0

Temuujin Dev
Temuujin Dev

Reputation: 921

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>

Upvotes: 9

Araoz
Araoz

Reputation: 183

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

Upvotes: 9

James KR
James KR

Reputation: 59

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>

Upvotes: 6

rxjmx
rxjmx

Reputation: 2181

Try this:

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

Upvotes: -2

Related Questions