简体   繁体   English

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

[英]Best way to find matching id's in an array of objects?

if I have this array of movie ids如果我有这个电影 ID 数组

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

and this array of objects.和这个对象数组。

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.我想返回一个匹配 id 的数组。 example [ 'Action', 'Thriller', 'Western' ].例如['动作','惊悚','西部']。

I have a solution already but feel that it could be better.我已经有一个解决方案,但觉得它可能会更好。 What is the best way to refactor this code?重构此代码的最佳方法是什么? Thanks.谢谢。

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

I would combine the filter and map array methods.我会结合filtermap数组方法。 Use filter to get a list of genres that are in your movies array, then use map to convert that to a list of names.使用filter获取movies数组中的流派列表,然后使用map将其转换为名称列表。

Example:例子:

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

Convert array=movies to Set first (it will improve performances when array=movies has a ton of elements), then use reduce to pull out all match items.首先将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 }, []) )

Use an array reducer to match ids together使用数组 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)

Simple:简单的:

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

Filter and map shorthand过滤器和映射速记

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

I bumped into a very similar problem this morning and took time out to address one possible oversight, in that the order of the original array is lost with the given solutions.今天早上我遇到了一个非常相似的问题,并抽出时间来解决一个可能的疏忽,因为给定的解决方案会丢失原始数组的顺序。

So I did some digging around and discussion with others (thanks discord,);所以我做了一些挖掘并与其他人讨论(感谢 discord,); I've come up with this solution that;我想出了这个解决方案;

  1. Keeps the order of the original array elements (as opposed to the order of the objects).保持原始数组元素的顺序(与对象的顺序相反)。
  2. Cleanses null-ish returns and removes any dupes.清理空返回并删除任何欺骗。
const movies = [37, 28, "bad data", false ,, 53, 53];
const genres = [
        {
            "id": 28,      
            "name": "Action"
        }, {
            "id": 10770,   
            "name": "TV Movie"
        },{
            "id": 53,      
            "name": "Thriller"
        },{
            "id": 10752,   
            "name": "War"
        }, {
            "id": 37,      
            "name": "Western"
        }];

const genreList  = new Set(
movies
    .map(   element       => genres
    .find(  objectElement => objectElement.id === element)?.name)
    .filter(Boolean));

//Return is [ 'Western', 'Action', 'Thriller' ]
console.log(Array.from(genreList));

Importantly, note how the order of the returned array matches the order of the original IDs.重要的是,请注意返回数组的顺序如何与原始 ID 的顺序相匹配。

Appreciated the other solutions posted.感谢发布的其他解决方案。 There are so many ways to achieve so much greatness.有很多方法可以实现如此伟大。 I would love to hear of where my solution could possibly be further improved.我很想知道我的解决方案在哪里可以进一步改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在具有 id 的数组与具有对象和相同 id 的数组之间查找匹配的 uniqueId - Find matching uniqueId between array with id's and array with objects and same id's 比较 2 个对象数组并找到匹配的颜色 id,然后创建一个新数组 Javascript - Compare 2 array's of objects and find matching color id's then create a new array Javascript 迭代嵌套的对象数组,查找 id 并更新与 id 匹配的对象 - Iterate nested array of objects, find id and update object matching the id 查找给定字符串的数组匹配元素的最佳方法 - Best way to find matching element of array for given string 在javascript中搜索对象数组以查找另一个数组的最佳方法是什么? - What is the best way to search an array of objects to find another array in javascript? 合并到匹配 id 的对象数组 - merge to objects array matching id 从对象数组中查找对象索引的最佳方法是什么 - javascript - What is the best way to find index of object from array of objects - javascript 从包含对象的数组中查找最小值的最佳方法 - Best way to find smallest value from array containing objects 在对象的javascript数组中查找下一个/上一个项目的最佳方法? - Best way to find the next/previous items in a javascript array of objects? 在二维数组中找到最短数组的最佳方法是什么? - What's the best way to find the shortest array in a two dimensional array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM