比较对象数组 [英] compare array of objects

查看:58
本文介绍了比较对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 function compare (arr1, arr2){
    //if object key value pair from arr2 exists in arr1 return modified array
    for (let obj of arr2) {
         if(obj.key === arr1.key){
             return obj
        }
     }
 }
 // Should return [{key: 1, name : "Bob", {key: 2, name : "Bill"}]

 compare([{key: 1}, {key: 2}], 
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])

我无法连接具有不同长度和属性的对象的循环数组.我尝试了循环和IndexOf,但是由于长度不同,因此无法以这种方式比较两个数组.我觉得过滤器可能是一个很好的工具,但是没有运气.有什么想法吗?

I am having a disconnect with looping arrays of objects with different lengths and properties. I have tried looping and IndexOf but due to different lengths, I cannot compare the two arrays that way. I feel like a filter might be a good tool but have had no luck. Any thoughts?

推荐答案

创建从第一个数组(键)设置属性,然后

Create a Set of properties from the 1st array (the keys), and then Array#filter the 2nd array (the values) using the set:

function compareBy(prop, keys, values) {
  const propsSet = new Set(keys.map((o) => o[prop]));

  return values.filter((o) => propsSet.has(o[prop]));
}

const result = compareBy('key', [{key: 1}, {key: 2}], 
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])

console.log(result);

这篇关于比较对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆