Reputation: 359
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?
Upvotes: 1
Views: 1887
Reputation: 33726
You can use the function Array.prototype.map
over the array genreIds
, extract the name, and finally filter out the undefined values (those not found objects).
const moviesNamesAndGenres = [ {id: 28, name: "Action"}, {id: 12, name: "Adventure"}, {id: 14, name: "Animation"}],
genreIds = [14, 28, 13],
result = genreIds.map(g => (moviesNamesAndGenres.find(m => m.id === g) || {}).name).filter(Boolean);
console.log(result);
Upvotes: 0
Reputation: 89374
You can first filter
out elements for which no matching object was found.
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
})
const result = test.filter(Boolean).map((el) => {
return el.name
})
console.log(result)
Upvotes: 1
Reputation: 76
The error is clear. You are trying to access a property of an undefined object. There is no match between the object with id:14 and the number 13 of the Array.
Upvotes: 0