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

4
  • use listOne.forEach... Commented Apr 25, 2019 at 10:53
  • Have you tried implementing it similar to the linked question? for loops and array prototype methods work just the same in typescript Commented Apr 25, 2019 at 10:54
  • What is expected output? Commented Apr 25, 2019 at 10:54
  • 1
    Possible duplicate of Compare to arrays of objects and update key in Angular Commented Apr 25, 2019 at 10:57

3 Answers 3

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.

Comments

Your Answer

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