【发布时间】:2019-10-17 05:21:58
【问题描述】:
我在 JavaScript 中有 2 个数组。其中一个需要根据另一个的属性进行过滤。
我有一个像这样的电影列表:
[
{
id: 1,
type: 'movies',
attributes: {
name: 'Batman'
}
},
{
id: 2,
type: 'movies',
attributes: {
name: 'Spiderman'
}
},
...
]
然后我有另一个数组,其中包含用户观看过的电影,但它们位于数组内的嵌套对象中,作为遵循 JSON API 规范的关系。
[
{
id: '1',
type: 'moviesWatched',
attributes: {
comment: 'Excellent film, would recommend to anyone who loves a action film!'
},
relationships: {
movie: {
data: {
type: 'movies',
id: 2
}
}
}
}
]
我需要实现的是我需要将来自watchList[].relationships.movie.data.id 的 id 与第一个数组交叉引用。显然,这个列表在生产中要长得多,但我希望实现的是拥有用户观看的电影的完整列表,其中电影的名称基于 2 个这样格式化的数组,以节省我不必存储不必要的数据库内部的数据。
数组的结果将类似于...
[
{
id: 1,
type: 'movies',
attributes: {
name: 'Batman'
},
meta: {
watched: false
}
},
{
id: 2,
type: 'movies',
attributes: {
name: 'Spiderman'
},
meta: {
watched: true
}
}
]
这是我目前所拥有的,它正在工作,但我不知道是否有更好的方法来解决它......
movies.map((movie) => {
const watched = watchedMovies.find((searchable) => {
return searchable.relationships.movie.data.id === searchable.id;
});
movie.meta.watched = watched || false;
return movie;
});
【问题讨论】:
-
您的问题不清楚。你似乎没有过滤任何东西;对于第一个数组中的每部电影,您只需将附加属性
meta.watched设置为true或false。另外,您自己尝试过什么? -
@slider 编辑了问题以获得我目前编码的内容
标签: javascript arrays