-1
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.

In AngularJs I have tried with below this related link for AngularJs

But how to integrate with Angular 6 with Typescript.

And expected output is listOne: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ]

3 Answers3

1

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);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
0

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;
    }
}
MonkeyScript
  • 4,776
  • 1
  • 11
  • 28
0

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. but i'm looking for Angular 2+ Typescript.