是否可以通过(例如,“id”)进行排序和分组,并通过使用Lodash添加密钥的所有唯一值(例如:支付)来更新元素的值? 例如,这个数组可以在下面:
[
{
id: 1,
payout: 15,
numOfPeople: 4
},
{
id: 1,
payout: 12,
numOfPeople: 3
},
{
id: 2,
payout: 6,
numOfPeople: 5
},
{
id: 2,
payout: 10,
numOfPeople: 1
}
]
...使用LODASH转换成下面的那个:
// Notice the Sum of all payout reflects the total sum of all
// payout with id=1 or id=2 (for a specific id Group)
[
{
id: 1,
payout: 27,
numOfPeople: 4
},
{
id: 1,
payout: 27,
numOfPeople: 3
},
{
id: 2,
payout: 16,
numOfPeople: 5
},
{
id: 2,
payout: 16,
numOfPeople: 1
}
]
你可以使用filter
,map
和reduce
的组合来做到这一点。
const arr = [
{
id: 1,
payout: 15,
numOfPeople: 4,
},
{
id: 1,
payout: 12,
numOfPeople: 3,
},
{
id: 2,
payout: 6,
numOfPeople: 5,
},
{
id: 2,
payout: 10,
numOfPeople: 1,
},
];
const idPayoutMap = {};
let result = arr.map(x => {
if (idPayoutMap['' + x.id] !== undefined) {
x.payout = idPayoutMap['' + x.id];
} else {
x.payout = arr
.filter(y => y.id === x.id)
.reduce((totalPayout, y) => y.payout + totalPayout, 0);
idPayoutMap['' + x.id] = x.payout;
}
return x;
});
console.log(result);
这是一个工作样本:Sample