简体   繁体   English

比较两个数组中的对象

[英]Comparing objects in two arrays

I want to compare objects in two arrays and if they are not the same, add them to the array.我想比较两个数组中的对象,如果它们不相同,则将它们添加到数组中。
first array第一个数组

[
  {
    "email": "a@a.com"
  },
  {
    "email": "b@b.com"
  },
  {
    "email": "c@c.com"
  },
  {
    "email": "d@d.com"
  }
]

secund array第二阵列

[
  {
    "email": "v@v.com"
  },
  {
    "email": "k@k.com"
  },
  {
    "email": "g@g.com"
  }
]

checking function检查功能

if($scope.participants.length > 0){
    result.forEach(function (resultElement) {   
        if(!$scope.participants.includes(resultElement) ) {
            $scope.participants.push(resultElement);
        }
    })
    result = [];
    console.log($scope.participants);
}

I checked the debug and it drops on the if condition.我检查了调试,它在 if 条件下下降。

You need to understand that two objects are not equal and the same.您需要了解两个对象不相等和相同。

For example {} === {} returns false例如 {} === {} 返回 false

if you want to compare objects you need to compare each primitive element of each object.如果要比较对象,则需要比较每个对象的每个原始元素。

Primitives include numbers, strings, booleans, etc and not objects or arrays (which are also objects).原语包括数字、字符串、布尔值等,而不是对象或数组(它们也是对象)。

 b1 = [ { id: 0, email: 'john@' }, { id: 1, email: 'mary@' }, { id: 2, email: 'pablo@' }, { id: 3, email: 'escobar@' } ]; b2 = [ { id: 0, email: 'john@' }, { id: 1, email: 'mary@' } ]; var res = this.b1.filter(item1 => !this.b2.some(item2 => (item2.id === item1.id && item2.name === item1.name))) console.log("check more is working",res);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM