在对象数组中查找匹配ID的最佳方法?

时间:2018-08-06 21:22:48

标签: javascript arrays refactoring

如果我有这个电影ID数组

movies = [28, 14, 100, 53, 37]

和这个对象数组。

genres = [
      {id: 28, name: "Action"},
      {id: 10770, name: "TV Movie"},
      {id: 53, name: "Thriller"},
      {id: 10752, name: "War"},
      {id: 37, name: "Western"}
    ]

我想返回一个匹配ID的数组。例如['Action','Thriller','Western']。

我已经有一个解决方案,但感觉可能会更好。重构此代码的最佳方法是什么?谢谢。

genre_array = []
movies.forEach(function(e){
  genres.forEach(function(element){
    if (element.id == e) {
     genre_array.push(element.name)
    } 
  });
});

5 个答案:

答案 0 :(得分:2)

我将结合使用filtermap数组方法。使用filter获取movies数组中的流派列表,然后使用map将其转换为名称列表。

示例:

const movies = [28, 14, 100, 53, 37]

const genres = [
      {id: 28, name: "Action"},
      {id: 10770, name: "TV Movie"},
      {id: 53, name: "Thriller"},
      {id: 10752, name: "War"},
      {id: 37, name: "Western"}
    ]

// I would like to return an array of the matching ids. example [ 'Action', 'Thriller', 'Western' ].

console.log(genres.filter(g => movies.includes(g.id)).map(g => g.name))

答案 1 :(得分:1)

使用array reducer将ID匹配在一起

const movies = [28, 14, 100, 53, 37]

const genres = [
  {id: 28, name: "Action"},
  {id: 10770, name: "TV Movie"},
  {id: 53, name: "Thriller"},
  {id: 10752, name: "War"},
  {id: 37, name: "Western"}
]

let genre_array = genres.reduce((arr, itm) => movies.includes(itm.id) ? arr.concat(itm.name) : arr, [])

console.log(genre_array)

答案 2 :(得分:0)

简单:

const movies = [28, 14, 100, 53, 37]

const genres = [{
    id: 28,
    name: "Action"
  },
  {
    id: 10770,
    name: "TV Movie"
  },
  {
    id: 53,
    name: "Thriller"
  },
  {
    id: 10752,
    name: "War"
  },
  {
    id: 37,
    name: "Western"
  }
]
let genre_array = [];
genres.forEach(function(element) {
  if (movies.includes(element.id)) {
    genre_array.push(element.name)
  }
});
alert(genre_array);

答案 3 :(得分:0)

首先将array=movies转换为Set(当array=movies有大量元素时,它将提高性能),然后使用reduce提取所有匹配项。

let movies = [28, 14, 100, 53, 37, 28]

let genres = [
      {id: 28, name: "Action"},
      {id: 10770, name: "TV Movie"},
      {id: 53, name: "Thriller"},
      {id: 10752, name: "War"},
      {id: 37, name: "Western"}
    ]

let indexes = new Set(movies)

console.log(
  genres.reduce((pre, cur) => {
    indexes.has(cur.id) && pre.push(cur.name)
    return pre
  }, [])
)

答案 4 :(得分:0)

过滤和映射速记

const movies = [28, 14, 100, 53, 37],
genres = [
  {id: 28, name: "Action"},
  {id: 10770, name: "TV Movie"},
  {id: 53, name: "Thriller"},
  {id: 10752, name: "War"},
  {id: 37, name: "Western"}
],
genreList = genres  // filter and a map - shorthand
  .filter(({id}) => movies.includes(id))
  .map(({name})  => name);
console.log(genreList);