【发布时间】:2019-11-05 19:52:38
【问题描述】:
我有订单对象
{
someUserData,
createdAt: 2019-11-05T18:32:25.199+00:00,
total: 5
}
我想实现这种数据结构:
{
2019: {
0: 5,
1: 100
total: 999
}
}
2019 年 - 年
0,1 等 - 月份,右侧的总值
总计:年收入
我试过这个:
calculateMonthlyRevenue = () => {
const { orders } = this.state;
const ordersMonthly = orders.map(x =>({
...x,
year: new Date(x.createdAt).getFullYear(),
month: new Date(x.createdAt).getMonth(),
}
));
const sumPerMonth = ordersMonthly.reduce((acc, cur) => {
acc[cur.year] = acc[cur.year] + cur.total || cur.total;
acc[cur.month] = acc[cur.month] + cur.total || cur.total;
return acc;
}, {})
};
acc 给我
{
10: amount of all Novembers throught history,
2019: I get the total amount, that is good but the data structure is not
what I need.
}
我试过这个:
acc[cur.year][cur.month] = acc[cur.year][cur.month] + cur.total || cur.total;
还有这个
acc[cur.year[cur.month]] = acc[cur.year[cur.month]] + cur.total || cur.total;
我还是卡住了。
上面一行代码给了我
9: amount
undefined: amount
最后一行代码抛出错误(Can not read property undefined of 10)
【问题讨论】:
标签: javascript object merge properties