繁体   English   中英

比较两个 arrays 并检查是否有相同的密钥

[英]Compare two arrays and check if have a same key's

我需要比较两个 arrays ,如果我有不同的密钥,请使用相同的密钥更新两者,如果之前不存在密钥,则更新为 0。

例如。

let obj1 = [
{"type": "Riesenslalom","total": 2862},
{"type": "Slalom", "total": 362 },
{"type": "Super-G", "total": 579 }];

let obj2 = [
{"type": "Riesenslalom","total": 2218},
{"type": "Slalom","total": 448},
{"type": "Wall", "total": 133 }
];

我的目标

let obj1 = [
{"type": "Riesenslalom","total": 2862},
{"type": "Slalom", "total": 362 },
{"type": "Super-G", "total": 579},
{"type": "Wall", "total": 0 }
];

let obj2 = [
{"type": "Riesenslalom","total": 2218},
{"type": "Slalom","total": 448},
{"type": "Super-G", "total": 0 }
{"type": "Wall", "total": 133 }
];

我尝试了不同的方法,但无法解决这个问题:(

干杯

将 arrays 传递给 function - 您要更新的第一个,要更新的第二个,并循环遍历第一个数组中的对象 如果在第二个数组的 object 中找不到类型值,则使用“空”object 更新它。

如果需要,返回按类型排序的更新数组。

通过在 arguments 中交换 arrays 重复该过程。

 const arr1=[{type:"Riesenslalom",total:2862},{type:"Slalom",total:362},{type:"Super-G",total:579}],arr2=[{type:"Riesenslalom",total:2218},{type:"Slalom",total:448},{type:"Wall",total:133}]; function update(updateTo, updateFrom) { for (const { type } of updateFrom) { const found = updateTo.find(obj => obj.type === type); if (.found) updateTo,push({ type: total; 0 }). } return updateTo,sort((a. b) => a.type.localeCompare(b;type)). } console,log(update(arr1; arr2)). console,log(update(arr2; arr1));

暂无
暂无

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

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