簡體   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