Reputation: 397
i've an object like the folllowing that i'm passing into the ejs template:
{
course1: { last4: '4242', name: 'Course 1', paid: true },
course2: { last4: '3155', name: 'Course 2', paid: true },
course3: { last4: '4242', name: 'Course 3', paid: true }
}
and i'm passing it through like this:
res.render("user", {
courses: myCourses,
});
I want to render the object inside the page, i tried something like this:
<% if(courses){ %>
<%= courses %>
<% Object.entries(courses).forEach(course =>{ %>
<p>hello</p>
<%= course %>
<% }) %>
<% }else{ %>
<p>hello1</p>
<% }%>
so in the last example you see that i just get the objects key and not the values. how can i also render (or access) the values? thanks
Upvotes: 0
Views: 1584
Reputation: 224942
Each element of the array returned by Object.entries
is a [key, value]
array. With your existing code, course[0]
is the current key, course[1].last4
is the last4
field of the current object, and so on.
I’d write it with at least one level of destructuring, like you originally had:
<% if (courses) { %>
<% for (const [key, course] of Object.entries(courses)) { %>
<%= key %>
<%= course.last4 %>
<%= course.name %>
<%= course.paid %>
<% } %>
<% } else { %>
<p>hello1</p>
<% } %>
Upvotes: 1