I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen.
const PopularBooks = [
{
id: 1,
title: "Harry Potter",
characters: [
{
id: 1,
name: "Harry Potter",
},
{
id: 2,
name: "Hermione",
},
{
id: 3,
name: "Ron",
},
],
{
id: 2,
title: "Lord of the Rings",
characters: [
{
id: 4,
name: "Frodo",
},
{
id: 5,
name: "Legolas",
},
{
id: 6,
name: "Gandalf",
},
],
},
];
Although I can display everything properly, I am facing difficulty in displaying character names.
<div class="description">
<h1><%= book.title %></h1>
</div>
</div>
<div class="data-m1">
<h4>Characters</h4>
<div class="characters">
<% for (let i = 1; i < 4; i++) { %>
<div class="portrait">
<img class="book-c" src="/images/book-c-1.png" alt="book" />
<p><%= book.characters[0].name %></p>
</div>
<% } %>
</div>
</div>
When I change
<p><%= book.characters[0].name %></p>
to dynamically display all names using [i]
, it gives me an error: Cannot read properties of undefined (reading 'name')
. Any suggestions or better ways to handle this?
If you're curious about how I obtained the value of book
, here is the method:
router.get("/books/:title", function (req, res, next) {
const bookId = parseInt(req.params.title);
const book = data.PopularBooks.find((book) => book.id === bookId);
res.render("books", { book });
});