简体   繁体   English

如何比较两个 arrays 并在 id 匹配时更改名称?

[英]How to compare two arrays and change the name if id matches?

I have a student array like below我有一个学生数组,如下所示

student=[{id:1,name:'Sam',age:23},{id:2,name:'Jolia',age:23},{id:3,name:'Peter',age:23}]

And also I have another one which contains updated age values of some students like below for example而且我还有另一个包含一些学生的更新年龄值,例如下面

updated=[{id:2,age:25},{id:3,age:21}]

In this case I wanna find intersection by Id of these two arrays and change age values of student array with updated ones.在这种情况下,我想通过这两个 arrays 的 Id 找到交集,并用更新的值更改学生数组的年龄值。

Expected Result预期结果

 student=[{id:1,name:'Sam',age:23},{id:2,name:'Jolia',age:25},{id:3,name:'Peter',age:21}]

values of id:2 and id:3 changed as updated includes those id values. id:2 和 id:3 的值随着更新而改变,包括那些 id 值。

I tried to iterate two arrays by map but didn't work and didnt seem sensible to me.我试图通过 map 迭代两个 arrays 但没有奏效,对我来说似乎也不明智。

updated.map(e=>{
   if(e.id==student.map(j=>{j.id})){
     e.age=j.age;
   }
 }) 

 var student=[{id:1,name:'Sam',age:23},{id:2,name:'Jolia',age:23},{id:3,name:'Peter',age:23}]; var updated=[{id:2,age:25},{id:3,age:21}]; updated.forEach(delta => { student.forEach(record => { if (delta.id === record.id) { record.age = delta.age; return false; } }); }); console.log(student);

You can use simple for each logic to iterate over each element to update them.您可以对每个逻辑使用 simple 来迭代每个元素以更新它们。 Returning false in the inner forEach will result in it terminating once a match has been made.在内部 forEach 中返回 false 将导致它在匹配完成后终止。

 let updated=[{id:2,age:25},{id:3,age:21}]; let student=[{id:1,name:'Sam',age:23},{id:2,name:'Jolia',age:23},{id:3,name:'Peter',age:23}]; student.forEach(e =>{ let idx = updated.findIndex(u => u.id == e.id); if(idx >=0) { e.age = updated[idx].age; } }); console.log(student);

You can use forEach instead of map() for this scenario.对于这种情况,您可以使用forEach而不是map() Iterate over all students and update age based on the update array if id matches.如果 id 匹配,则迭代所有学生并根据更新数组更新年龄。 findIndex returns the index of first element in the array that satisfies the provided testing function findIndex返回数组中满足提供的测试 function 的第一个元素的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM