简体   繁体   中英

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.

You need to understand that two objects are not equal and the same.

For example {} === {} returns 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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