Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

node.js - How to iterate object in ejs?

Good day! I'm a beginner at Node.js. I have a problem with an iterating object on ejs. I've used the book object to retrieve all data from DB and tried to pass it using res.locals. I will use the object to display the book information on the front-end. I tried several ways to iterate object that I've stored on middleware and I'm stuck on it (such as iterating the books by its length and using forEach).

Middleware:

let book = await Book.find({});
res.locals.book = {book};
next();

EJS:

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

Result:

enter image description here

Is there another way to iterate and display it? Tyia!

question from:https://stackoverflow.com/questions/65557777/how-to-iterate-object-in-ejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can do something like this

<%if (book){%>
<%for (var result in book){%>
    <li>genre :<ul><%=for(genres in book[result].genre) {%>
        <li><%=book[result].genre[genres]%></li>
<%}%>
     </ul>
    </li>    
<li>title:<%=book[result].title %></li>
<li>copy:<%=book[result].copy %></li>
<li>cover:<%=book[result].cover %></li>
<li>author:<%=book[result].author %></li>
<li>price:<%=book[result].price %></li>
<li>description:<%=book[result].description %></li>
<li>language:<%=book[result].language %></li>
<li>release date:<%=book[result].release_date %></li>
<li>favorites:<%=book[result].favorites %></li>

<%}%> 

i hope this will helpful to you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...