我有一个对象列表,例如
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 device)
GBP: 2,098.17 (2 devices)
}
尝试添加另一个循环,但它没有按预期工作
分两部分完成此操作要容易得多。
首先
reduce
将其存储为具有分组值的数组。
然后循环(也可以减少)对象,并获取数组的和,并将
${array.length} devices
添加到字符串中:
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
}
}
let grouped = Object.values(usageCosts).reduce((p, c) => {
if (!p[c.currency]) p[c.currency] = [];
p[c.currency].push(c.yearlyUsage);
return p;
}, {});
for (var key in grouped) {
grouped[key] = `${grouped[key].reduce((a,b)=>a+b)} (${grouped[key].length}) devices`;
}
console.log(grouped)
解决方案如下:
const result = Object.values(usageCosts).reduce((acc, stat) => {
if (stat.currency && !acc[stat.currency]) {
acc[stat.currency] = {
total: 0,
devices: 0,
}
}
return {
...acc,
[stat.currency]: {
total: acc[stat.currency].total + stat.yearlyUsage,
devices: acc[stat.currency].devices + 1,
}
};
}, {});
结果,你将得到以下结构:
{
GBP: { total: 2098.17, devices: 2 },
EUR: { total: 522.3, devices: 1 }
}