[英]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.我有 2 个 arrays 对象。 Both arrays have the same length and the same id properties for each object:
arrays 对于每个 object 具有相同的长度和相同的 id 属性:
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?如何从 arr2 复制每个 object 的技能属性,并通过检查相关属性 ID 将其设置在 object 的第一个数组中?
For each value in arr1
, try to find a corresponding value in arr2
and update the skill property accordingly:对于
arr1
中的每个值,尝试在arr2
中找到对应的值并相应地更新技能属性:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.