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