Flignats
Flignats

Reputation: 1274

Compare to arrays of objects and update key in Angular

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?

Upvotes: 0

Views: 1457

Answers (4)

Geeky
Geeky

Reputation: 7496

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

Upvotes: 1

Robba
Robba

Reputation: 8314

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;
});

Upvotes: 0

Drake Boley
Drake Boley

Reputation: 41

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

Upvotes: 0

rrd
rrd

Reputation: 5967

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

Upvotes: 0

Related Questions