基于Id合并数组重复对象及accountList子数组问题求助
解决数组对象按Id合并并合并子数组的问题
我懂你遇到的麻烦啦——现在的代码在匹配到相同Id时,会直接覆盖accountList数组,而不是把两个数组的内容合并起来。这是因为你用的Object.assign或者扩展运算符都是直接替换对象属性,对于数组这种引用类型来说,就是直接换掉整个数组,而不会合并里面的元素。
咱们来修改代码,专门处理accountList的合并:
方法一:forEach循环修改
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 => { const match = result.find(r => r.Id === account.Id); if (match) { // 合并两个accountList,同时过滤掉空对象(和你的期望结果对齐) match.accountList = [...match.accountList, ...account.accountList].filter(item => Object.keys(item).length > 0); } else { // 新对象加入时也过滤空对象 result.push({ ...account, accountList: account.accountList.filter(item => Object.keys(item).length > 0) }); } }); console.log(JSON.stringify(result, null, 2));
方法二:用reduce简化代码
如果你更喜欢更简洁的写法,可以用数组的reduce方法:
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 } ] } ] const result = accounts.reduce((acc, current) => { const existingItem = acc.find(item => item.Id === current.Id); if (existingItem) { existingItem.accountList = [ ...existingItem.accountList, ...current.accountList ].filter(item => Object.keys(item).length > 0); } else { acc.push({ ...current, accountList: current.accountList.filter(item => Object.keys(item).length > 0) }); } return acc; }, []); console.log(JSON.stringify(result, null, 2));
关键说明
- 核心思路:不再直接替换整个对象,而是手动合并
accountList数组,用扩展运算符...把两个数组的元素整合到一起。 - 过滤空对象:因为原数组里有个空对象
{},而你的期望结果里没有这一项,所以用filter(item => Object.keys(item).length > 0)把它去掉。如果不需要过滤,可以直接删掉这个方法。
这样运行代码后,就能得到你想要的合并结果啦~
内容的提问来源于stack exchange,提问作者Ali Khalil
相关产品推荐
相关产品推荐

