我有一个数组:
[{id:1,val:2},{id:1,val:2},{id:2,val:2},{id:2,val:2}]
所需的输出:
[{id:1,val:[2,2]},{id:2,val:[2,2]}]
如何使用Lodash获得所需的结果?
答案 0 :(得分:0)
这是我使用香草javascript的方法:
const source = [{id:1,val:2},{id:1,val:2},{id:2,val:2},{id:2,val:2}]
console.log(source.reduce( (acc, curr) => {
const itemExists = acc.find(item => curr.id === item.id)
if(itemExists){
itemExists.val = [...itemExists.val, curr.val]
}else{
acc.push({id: curr.id, val: [curr.val]})
}
return acc;
}, []))