比较对象数组并更新角度6打字稿中的键

时间:2019-04-25 10:52:02

标签: javascript angular typescript angular6

listOne: [
{ 
  id: 1,
  compId: 11,
  active: false, 
},
{ 
  id: 2,
  compId: 22,
  active: false, 
},
{ 
  id: 3,
  compId: 33,
  active: false, 
},
]

listTwo: [
{ 
  id: 1,
  compId: 11,
  active: true, 
},
{ 
  id: 2,
  compId: 33,
  active: false, 
},
]

我有两个json,这里是如何与 compId 键进行比较,如果 compId,如何从 listTwo 中更新 listOne 中的活动密钥相同。

在AngularJs中,我尝试使用此相关链接for AngularJs

但是如何通过Typescript与Angular 6集成。

预期输出为 listOne: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ]

3 个答案:

答案 0 :(得分:1)

您可以像这样使用地图和过滤器

listOne = listOne.map(item => {
       let exist = listTwo.filter(c=>c.compId == item.compId)[0];
       if(exist != undefined){

           item.active = exist.active;
           return item;
       }else{
           return item;
       }
    });

let listOne= [
{ 
  id: 1,
  compId: 11,
  active: false, 
},
{ 
  id: 2,
  compId: 22,
  active: false, 
},
{ 
  id: 3,
  compId: 33,
  active: false, 
},
]

let listTwo= [
{ 
  id: 1,
  compId: 11,
  active: true, 
},
{ 
  id: 2,
  compId: 33,
  active: false, 
},
]

//let arr3 = [];

listOne = listOne.map(item => {
   let exist = listTwo.filter(c=>c.compId == item.compId)[0];
   if(exist != undefined){
       //item.id = exist.id;
       item.active = exist.active;
       return item;
   }else{
       return item;
   }
});

console.log(listOne);

答案 1 :(得分:0)

尝试一下

// Iterate over list one
for(let item of this.listOne){
    // Check if the item exist in list two
    if(this.listTwo.find(i=>i.compId==item.compId)){
        // Update key
        item.active = this.listTwo.find(i=>i.compId==item.compId).active;
    }
}

答案 2 :(得分:0)

我试图找到问题的解决方案。 因此,我们需要迭代两个 for 来检查每个数据,如下所示。 并且需要根据需要更换

for (const s of listOne) {
              for (const r of listTwo) {
                if (s.compId === r.compId) {
                  s.active = r.active;
                  break;
                }
              }
            }
  • 我已经提到了链接,该链接可用于 AngularJS 。但我正在寻找Angular 2+打字稿。