【问题标题】:how to check for same objects in two different arrays in JavaScript如何在 JavaScript 中检查两个不同数组中的相同对象
【发布时间】:2021-11-06 07:42:58
【问题描述】:

我想做这样的事情,

let array1 = [{obj1}, {obj2},{obj3}] 
let array2 = [{obj1}, {obj4},{obj5}]

输出应该是这样的

{obj1}

【问题讨论】:

标签: javascript arrays object intersection


【解决方案1】:

这适用于简单的对象。

请记住,它不适用于基于函数的属性。

const array1 = [{a:1}, {b:2},{c:3}] 
const array2 = [{a:1}, {d:4},{e:5}]

const array1Stringify = array1.map(el => JSON.stringify(el));
const array2Stringify = array2.map(el => JSON.stringify(el));

const result = array1Stringify.filter(el => array2Stringify.includes(el)).map(el => JSON.parse(el));

console.log(result);

【讨论】:

  • 对比JSON字符串会有限制,不推荐。
【解决方案2】:

正如所评论的,您的大部分问题是定义如何评估您的对象相等性。一旦你解决了这个问题,只需检查另一个数组中一个数组的匹配项,就可以得到你想要的匹配项。最易读和最幼稚的方式,带有双 for。

let array1 = ['hello', 'world', 'I rule'] 
let array2 = ['hello', 'whatever', 'hey brother']

let matches = [];
for (let i = 0; i < array1.length; i++) {
    for (let j = 0; j < array2.length; j++) {
        if (array1[i] === array2[j]) { //equality for object problem here
            matches.push(array1[i]);
        }
    }
}

console.log({matches});

【讨论】:

    【解决方案3】:

    【讨论】:

      【解决方案4】:

      用大括号括起来有什么特别的原因吗? 这是为您提供的解决方案。希望这个答案可能对您的问题有所帮助。

      const obj1 = {a: 'foo1', b: 'bar1'};
      const obj2 = {a: 'foo2', b: 'bar2'};
      const obj3 = {a: 'foo3', b: 'bar3'};
      const obj4 = {a: 'foo4', b: 'bar4'};
      const obj5 = {a: 'foo5', b: 'bar5'};
      
      let array1 = [obj1, obj2, obj3] 
      let array2 = [obj1, obj4, obj5]
      
      let result = array1.filter(o1 => array2.some(o2 => o1 === o2));
      
      console.log(result);
      

      如果您想对每个对象进行对象深度比较,请访问this solution

      【讨论】:

      • 您的解决方案将无法正常工作。举个例子:const obj1 = {a: 'foo1', b: 'bar1'}; const obj2 = {a: 'foo2', b: 'bar2'}; const obj3 = {a: 'foo3', b: 'bar3'}; const obj4 = {a: 'foo4', b: 'bar4'}; const obj5 = {a: 'foo5', b: 'bar5'}; let array1 = [{a: 'foo1', b: 'bar1'}, obj2, obj3] let array2 = [{a: 'foo1', b: 'bar1'}, obj4, obj5] let result = array1.filter(o1 =&gt; array2.some(o2 =&gt; o1 === o2)); console.log(result);
      • 我刚刚更新了关于对象深度比较的答案。您可以使用对象深度比较方法代替o1 === o2
      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      相关资源
      最近更新 更多