Heim > Fragen und Antworten > Hauptteil
P粉4818158972023-08-15 15:34:26
这个任务分为两个部分会更容易。
首先,将其reduce
为一个包含分组值的数组。
然后循环遍历(也可以使用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)