我试图根据 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 } ] }]
添加回答
举报
0/150
提交
取消