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?

3
  • so you want to compare listone and listtwo,as id:2 exists in both them ,output should be listone[2].selected=true? Commented Nov 9, 2016 at 15:45
  • please let us know what worked for you Commented Nov 9, 2016 at 18:42
  • @geeky I'm not looking for a new output, only to update listOne's selected property if the same id exists in listTwo Commented Nov 9, 2016 at 19:57

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, how can I use this with angular.forEach?
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').

1 Comment

Nice tip, but I'm looking to keep the array intact and only updated the selected property.
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

1 Comment

Iodash is a great suggestion, but I'd prefer to not depend on a library for this if possible.
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;
});

1 Comment

great suggestion, trying to use this within an angular.forEach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.