我有一个对象列表,如下:
const usageCosts = {
224910186407: {
deviceId: "224910186407",
currency: "GBP",
yearlyUsage: 1480.81
},
224910464538: {
deviceId: "224910464538",
currency: "GBP",
yearlyUsage: 617.36
},
224910464577: {
deviceId: "224910464577",
currency: "EUR",
yearlyUsage: 522.3
}
}
我正在按货币进行求和,如下:
const totalYearlyCost = Object.values(usageCosts).reduce(
(acc: { [key: string]: any }, stat: any) => {
if (stat.currency && !acc[stat.currency]) {
acc[stat.currency] = 0
}
return {
...acc,
[stat.currency!]: acc[stat.currency!] + stat.yearlyUsage,
}
},
{},
)
它返回一个对象,如下:
{
EUR: 522.3
GBP: 2,098.17
}
我还想返回每种货币的设备总数,类似于:
{
EUR: 522.3 (1个设备)
GBP: 2,098.17 (2个设备)
}
尝试添加另一个循环,但结果不如预期。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号