如何将对象内部的属性合并为一个属性?

问题描述 投票:1回答:1

我有订单对象

{
  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

代码的最后一行抛出错误(无法读取属性未定义的10)

javascript object merge properties
1个回答
0
投票

您可以分割ISO 8601日期字符串以获取年份和月份,并使用默认对象(年份总计)和默认值零(月份)。

向两个目标添加原始对象的总数。

var data = [{ someUserData: 'foo', createdAt: '2019-11-05T18:32:25.199+00:00', total: 5 }],
    result = data.reduce((r, { createdAt, total }) => {
        var [year, month] = createdAt.split('-', 2);
        r[year] = r[year] || { total: 0 };
        r[year][month -1 ] = (r[year][month - 1] || 0) + total;
        r[year].total += total;
        return r;
    }, {});

console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.