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:'email1@gmail.com'}, {id:2, name:'Jane', email:'email2@gmail.com'}]
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:'email1@gmail.com'}, {id:2, name:'Jane', email:'email2@gmail.com'} ]; 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);
You could do something like this.
const arr1 = [{id: 1, name: "Dave", email: "email1@gmail.com"}, {id: 2, name: "Jane", email: "email2@gmail.com"}]; const arr2 = [{id: 1, profession: "programmer", skill: "JS"}, {id: 2, profession: "Sales person", skill: "sales"}]; console.log(arr1); arr2.forEach((el2) => { let result = arr1.find((el1) => el1.id === el2.id) if (result) { result.skill= el2.skill; } }) console.log(arr1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.