如何以高效的方式在JavaScript中进行一些数组比较

问题描述 投票:0回答:1

TMDB API返回一个如下所示的电影对象数组:

{
"vote_count": 1527,
"id": 338952,
"video": false,
"vote_average": 7,
"title": "Fantastic Beasts: The Crimes of Grindelwald",
"popularity": 272.487,
"poster_path": "/uyJgTzAsp3Za2TaPiZt2yaKYRIR.jpg",
"original_language": "en",
"original_title": "Fantastic Beasts: The Crimes of Grindelwald",
"genre_ids": [
   10751,
   14,
   12
],
"backdrop_path": "/xgbeBCjmFpRYHDF7tQ7U98EREWp.jpg",
"adult": false,
"overview": "Gellert Grindelwald has .....",
"release_date": "2018-11-14"
}

它们还提供了一个API,用于通过键和标签返回对象数组中的所有可用类型:

genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
}
]

我需要做的是从现在播放的API中获取所有独特类型的列表及其标签值。

所以我的问题不是关于如何做到这一点,而是什么是最干净,最有效的方法。

我的尝试:

let uniqueIds = new Set(), genres;

// First get all available unique genre IDs from the now playing list
for(var i = 0; i < this.state.items.length; i++){
    for(var x = 0; x < this.movies[i].genre_ids.length; x++){
        uniqueIds.add(this.movies[i].genre_ids[x])
    }
}

// build array of genre objects from unique genre IDs
genres = this.genres.filter((genre) => uniqueIds.has(genre.id));
javascript ecmascript-6
1个回答
3
投票

1)对于数组中的每个对象,抓住genre_ids

2)filter输出id包含在ids数组中的类型对象。

const api = [{"vote_count":1527,"id":338952,"video":false,"vote_average":7,"title":"Fantastic Beasts: The Crimes of Grindelwald","popularity":272.487,"poster_path":"/uyJgTzAsp3Za2TaPiZt2yaKYRIR.jpg","original_language":"en","original_title":"Fantastic Beasts: The Crimes of Grindelwald","genre_ids":[10751,14,12],"backdrop_path":"/xgbeBCjmFpRYHDF7tQ7U98EREWp.jpg","adult":false,"overview":"Gellert Grindelwald has .....","release_date":"2018-11-14"},{"vote_count":1527,"id":338952,"video":false,"vote_average":7,"title":"Fantastic Beasts: The Crimes of Grindelwald","popularity":272.487,"poster_path":"/uyJgTzAsp3Za2TaPiZt2yaKYRIR.jpg","original_language":"en","original_title":"Fantastic Beasts: The Crimes of Grindelwald","genre_ids":[10751,14,16],"backdrop_path":"/xgbeBCjmFpRYHDF7tQ7U98EREWp.jpg","adult":false,"overview":"Gellert Grindelwald has .....","release_date":"2018-11-14"}];
const genres = [{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"}];

// [].concat(...arr) flattens consequtive arrays down
const idArr = [].concat(...api.map(obj => obj.genre_ids));
const matchingGenres = genres.filter(obj => idArr.includes(obj.id));

console.log(matchingGenres);
© www.soinside.com 2019 - 2024. All rights reserved.