Exploring my collection of movies, I discovered that each movie contains an array of characters. My goal is to display specific information about each character (such as their name and age) when clicked on, requiring me to obtain the id
of each character.
const PopularBooks = [
{
id: 1,
title: "Harry Potter",
characters: [
{
id: 10,
name: "Harry Potter",
},
{
id: 11,
name: "Hermione",
},
{
id: 12,
name: "Ron",
},
],
{
id: 2,
title: "Lord of the Rings",
characters: [
{
id: 13,
name: "Frodo",
},
{
id: 14,
name: "Legolas",
},
{
id: 15,
name: "Gandalf",
},
],
},
];
In the main book page, I have portraits of each character displayed as images. Clicking on a character leads to another webpage where the character's id is passed as a parameter.
<% book.characters.forEach(character => { %>
<div class="portrait">
<a href="/character/<%= character.id %>">
<img
src="/images/characters/book-c-<%= character.id %>.png"
/>
</a>
<p><%= character.name %></p>
</div>
<% }); %>
Although I successfully set up the router function to handle characterIds, I encountered an issue when trying to compare the characterId
with the actual id
within the data array. This resulted in an error:
Cannot read properties of undefined (reading 'find')
const data = require("../data");
router.get("/character/:character", function (req, res, next) {
const characterId = parseInt(req.params.character);
const character = data.PopularBooks.characters.find(
(characters) => characters.id === characterId
);
console.log(characterId);
console.log(character);
res.render("character", { character });
});
I am striving to create unique pages for each character, but I need guidance on resolving this error. What steps can I take to correct this issue?