0

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?

Flignats
  • 1,234
  • 10
  • 21

4 Answers4

1

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>

Hope this helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
0

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').

rrd
  • 5,789
  • 3
  • 28
  • 36
0

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

Community
  • 1
  • 1
0

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;
});
Robba
  • 7,684
  • 12
  • 48
  • 76