如何迭代与另一个数组中的公共元素匹配的对象数组并返回"name"的键值



我想映射到一个对象数组上。如果每个对象的id与另一个数组的id匹配,那么我想返回电影名称。

我已经看到了关于这一点的其他线程,并使用了.map.find,但是由于某种原因,我的代码没有返回我想要的结果。

在JavaScript对象数组中按id查找对象

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
})

在这一点上,我在数组中有两个匹配的id对象。

{ id: 14, name: 'Animation' }
{ id: 28, name: 'Action' }
undefined

我现在想返回每个对象的name

这是我的代码尝试:

const result = test.map((el) => {
return el.name
})
console.log(result)

现在我得到了:

TypeError: Cannot read property 'name' of undefined

有人能帮我理解为什么吗?

您可以先从未找到匹配对象的元素中取出filter

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)

错误很明显。您正试图访问一个未定义对象的属性。id为14的对象和数组的数字13之间没有匹配项。

您可以在数组genreIds上使用函数Array.prototype.map,提取名称,最后过滤掉未定义的值(未找到的对象(。

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);

最新更新