我試圖根據 Id 合并對象,并合并每個account(對象)內的每個數組,但不是合并 accountList 的內容,如果有匹配的 id,代碼會覆蓋數組。我創建了一個新數組并使用 .find 方法根據那里的 id 查找匹配的對象,但堅持如何將它們合并accountList在一起const accounts = [ { "Id": 103, "accountList": [ {} ] }, { "Id": 103, "accountList": [ { "tokenId": "5aasdasdsdnjn3434nadd", "featureId": 2840 } ] }, { "Id": 112, "accountList": [ { "tokenId": "5d30775bef4a722c38aefaaa", "featureId": 2877 } ] }, { "Id": 112, "accountList": [ { "tokenId": "5d30775bef4a722c38aefccc", "featureId": 2856 } ] }]let result = [];accounts.forEach(account => { let match = result.find(r => r.Id === account.Id); // console.log(match) if(match) { Object.assign(match, account); //tried using spread operator instead of object assign, but didnt work // match = {...match, ...account} } else { result.push(account); }});console.log( JSON.stringify(result, null, 2))我需要的結果是根據對象的 id 合并對象,并將它們的內容合并accountList在一起,如下所示:[ { "Id": 103, "accountList": [ { "tokenId": "5aasdasdsdnjn3434nadd", "featureId": 2840 } ] }, { "Id": 112, "accountList": [ { "tokenId": "5d30775bef4a722c38aefaaa", "featureId": 2877 }, { "tokenId": "5d30775bef4a722c38aefccc", "featureId": 2856 } ] }]
合并數組中的重復對象并合并每個對象的子數組
一只斗牛犬
2021-09-30 11:00:22