【问题标题】:How to merge properties inside object into one property?如何将对象内部的属性合并为一个属性?
【发布时间】: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


    【解决方案1】:

    您可以拆分 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);

    【讨论】:

    • 看到答案如此简单,我感到很愚蠢。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多