I would like to map over an array of objects. If the id
of each object matches the id
from another array then I want to return the movie name.
I have seen other threads about this and have used .map
and .find
however for some reason my code does not return the result I want.
Find object by id in an array of JavaScript objects
const moviesNamesAndGenres = [
{id: 28, name: "Action"},
{id: 12, name: "Adventure"},
{id: 14, name: "Animation"}
]
const genreIds = [14, 28, 13];
const test = genreIds.map((genreId) => {
const matchedGenres = moviesNamesAndGenres.find((movieObj) => {
return movieObj.id === genreId
})
return matchedGenres // this returns the matching objects, cool
})
At this point I have the following as two objects in the array for ids that matched.
{ id: 14, name: 'Animation' }
{ id: 28, name: 'Action' }
undefined
I would now like to return the name
for each object
here is my code attempt:
const result = test.map((el) => {
return el.name
})
console.log(result)
Now I get:
TypeError: Cannot read property 'name' of undefined
could someone help me understand why?