Search code examples
javascriptarraysecmascript-6javascript-objectsecmascript-5

How to copy skill property from each object in the 2nd and set that skill property for each object in the 1st array based on property id? (JS)


I have 2 arrays of objects. Both arrays have the same length and the same id properties for each object:

const arr1 = [{id:1, name:'Dave', email:'[email protected]'}, {id:2, name:'Jane', email:'[email protected]'}]
const arr2 = [{id:1, profession:'programmer', skill:'JS'}, {id:2, profession:'Sales person', skill:'sales'}]

How can I copy skill property for each object from arr2 and set it in the first array of object by checking the related property id?


Solution

  • For each value in arr1, try to find a corresponding value in arr2 and update the skill property accordingly:

    arr1.forEach(v1 => v1.skill = arr2.find(v2 => v1.id === v2.id)?.skill);
    

    Complete snippet:

    const arr1 = [
      {id:1, name:'Dave', email:'[email protected]'},
      {id:2, name:'Jane', email:'[email protected]'}
    ];
    const arr2 = [
      {id:1, profession:'programmer', skill:'JS'},
      {id:2, profession:'Sales person', skill:'sales'}
    ];
    
    arr1.forEach(v1 => v1.skill = arr2.find(v2 => v1.id === v2.id)?.skill);
    
    console.log(arr1);