I have an array of movies and inside each movie is another array for characters. When I click on a character I’d like to show various bits of information about them (name, age, etc.) and in order to do that, I need 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",
},
],
},
];
Inside the main book page I have each character displayed inside an image and when you click on the character it sends you to another web page where the params is the characters id.
<% 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>
<% }); %>
I have set the params in my router function to a characterId function which works fine, however when I try sorting through my data array again to compare the characterId function to the characters actual id, the character id is returning as undefined and I’m left with this 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 need this information to set up a page for each unique character. What am I doing wrong to cause this error and how can I fix it?
>Solution :
You are trying to access the characters array of a specific book, but you are currently searching for the character within the entire PopularBooks array. You need to first find the correct book by its ID and then search for the character:
...
//find the book containing the character
const bookWithCharacter = data.PopularBooks.find((book) =>
book.characters.some((character) => character.id === characterId)
);
if (!bookWithCharacter) {
//if ID is not found in any book
return res.status(404).send("Character not found");
}
//find the specific character within the book
const character = bookWithCharacter.characters.find(
(char) => char.id === characterId
);
....