计算每个月使用日期创建的总包裹数

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

我正在多个包裹的json中获取日期。日期通常会告诉您创建特定包裹的日期和时间。因此,该日期我想计算每个月创建的包裹数量。我以前从未做过此事,而且我不确定stackoverflow的哪个线程可以在这方面帮助我。我非常感谢您提供解决此帮助的任何解释或代码参考。这是我的示例JSON结果

[
  {
    "createdAt": "2019-12-30T04:36:05.001Z"
  },
  {
    "createdAt": "2019-12-06T08:58:23.030Z"
  },
  {
    "createdAt": "2020-01-08T19:00:21.873Z"
  },
  {
    "createdAt": "2020-01-10T14:55:50.781Z"
  },
  {
    "createdAt": "2019-12-21T13:05:09.983Z"
  },
  {
    "createdAt": "2020-01-15T12:10:20.316Z"
  },
  {
    "createdAt": "2020-01-14T06:47:36.078Z"
  },
  {
    "createdAt": "2020-02-15-T06:47:36.078Z"
  }
]

我正在与angular一起工作,因此我将从服务中获取此数据。因此,现在我需要显示按月创建的包裹总数。

javascript typescript
2个回答
2
投票

您可以将ISO 8601日期字符串的一部分作为键并用一个对象计数。

var data = [{ createdAt: "2019-12-30T04:36:05.001Z" }, { createdAt: "2019-12-06T08:58:23.030Z" }, { createdAt: "2020-01-08T19:00:21.873Z" }, { createdAt: "2020-01-10T14:55:50.781Z" }, { createdAt: "2019-12-21T13:05:09.983Z" }, { createdAt: "2020-01-15T12:10:20.316Z" }, { createdAt: "2020-01-14T06:47:36.078Z" }, { createdAt: "2020-02-15-T06:47:36.078Z" }],
    result = data.reduce((r, { createdAt }) => {
        var key = createdAt.slice(0, 7);
        r[key] = (r[key] || 0) + 1;
        return r;
    }, {});

console.log(result);

1
投票

您可以使用Array.prototype.reduce()总结您的记录。

Array.prototype.reduce()

,如果您的const src = [{"createdAt":"2019-12-30T04:36:05.001Z"},{"createdAt":"2019-12-06T08:58:23.030Z"},{"createdAt":"2020-01-08T19:00:21.873Z"},{"createdAt":"2020-01-10T14:55:50.781Z"},{"createdAt":"2019-12-21T13:05:09.983Z"},{"createdAt":"2020-01-15T12:10:20.316Z"},{"createdAt":"2020-01-14T06:47:36.078Z"},{"createdAt":"2020-02-15T06:47:36.078Z"}], summary = src.reduce((res,{createdAt}) => { const year = new Date(createdAt).getFullYear(), month = new Date(createdAt).getMonth()+1 res[`${year}-${month}`] = (res[`${year}-${month}`] || 0) + 1 return res }, {}) console.log(summary) 字符串以createdAt构造函数可能会解析的任何方式进行格式化,而不仅是ISO格式的日期,则可以使用以上内容。

© www.soinside.com 2019 - 2024. All rights reserved.