问题描述:

How can I compare two arrays of objects and update a key if an object exists in both arrays?

$scope.listOne = [

{id: 1, selected: false},

{id: 2, selected: false},

{id: 3, selected: false}

];

$scope.listTwo = [

{id: 4, color: orange},

{id: 5, color: blue},

{id: 2, color: green}

];

Using the above objects, how can I compare them and have listOne[1].selected updated to true?

网友答案:

Here, i am trying to loop through listone and checking if there is such key in listtwo if so making listone's selected property to true

This is done in vanila javascript

var listOne = [{
  id: 1,
  selected: false
}, {
  id: 2,
  selected: false
}, {
  id: 3,
  selected: false
}];

var listTwo = [{
  id: 4,
  color: "orange"
}, {
  id: 5,
  color: "blue"
}, {
  id: 2,
  color: "green"
}];



angular.forEach(listOne, function(value) {
  for (var key in listTwo) {
    if (listTwo[key]["id"] == value.id) {
      value.selected = true;
    }
  }
});
console.log(listOne);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
网友答案:

My first thought that jumps to mind is to use a lodash function:

let a = [{ id: 1, selected: false }];
let b = [{ id: 1, selected: false }, { id: 2, selected: true }];
let result = _.intersectionWith(a, b, _.isEqual);

'result' should be an array with one element, that part which match (ie., 'a').

网友答案:

Look into lodash _.some (https://lodash.com/docs/4.16.6#some)

Otherwise you could loop through the arrays, JSON.stringify each object and check for equality that way like this answer:

Object comparison in JavaScript

网友答案:

In just plain Javascript:

$scope.listOne.filter(function(item) {
    return !!$scope.listTwo.find(function(innerItem) {
        innerItem.id == item.id;
    });
})
.forEach(function(item) {
    item.selected = true;
});
相关阅读:
Top