简体   繁体   English

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

[英]compare to arrays of objects and update key in angular 6 typescript

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, 
},
]

I have two json, here how to compare with compId key and update the active key in listOne from listTwo if compId is same. 我有两个json,在这里如何与compId键进行比较,如果compId相同, 如何listTwo更新listOne中的活动键。

In AngularJs I have tried with below this related link for AngularJs 在AngularJs中,我尝试使用此相关链接查找AngularJs

But how to integrate with Angular 6 with Typescript. 但是如何使用Typescript与Angular 6集成。

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

You can use map and filter like this 您可以像这样使用地图和过滤器

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

Try this, 尝试这个,

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

I tried and got solution for the question. 我尝试过并找到了解决问题的方法。 So we need to iterate two for to check each data like below. 因此,我们需要遍历两个用于检查每个数据如下喜欢。 And need to replace as need 并根据需要更换

for (const s of listOne) {
              for (const r of listTwo) {
                if (s.compId === r.compId) {
                  s.active = r.active;
                  break;
                }
              }
            }
  • I have already mentioned the link which the answer available for AngularJS . 我已经提到了AngularJS可用答案​​的链接。 but i'm looking for Angular 2+ Typescript. 但是我正在寻找Angular 2+ Typescript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM