比较对象数组并更新Angular中的键 [英] Compare to arrays of objects and update key in Angular

查看:89
本文介绍了比较对象数组并更新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}
];

使用上述对象,我如何比较它们并将listOne [1] .selected更新为true?

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

推荐答案

在这里,我试图遍历listone并检查listtwo中是否存在这样的键,如果这样的话,则将listone的selected属性设置为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

这是在vanila javascript中完成的

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>

希望这会有所帮助

这篇关于比较对象数组并更新Angular中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆