将密钥添加到countBy函数

2022-03-09 00:00:00 javascript lodash

我有一个数据源,如下所示

[
  {
    "physicalId": 2110,
    "closedDate": "2017-06-25T00:00:00.000Z",
    "allDay": true
  },
  {
    "physicalId": 2111,
    "closedDate": "2017-06-24T00:00:00.000Z",
    "allDay": true
  },
  {
    "physicalId": 2111,
    "closedDate": "2017-06-25T00:00:00.000Z",
    "allDay": true
  },
  {
    "physicalId": 4299,
    "closedDate": "2017-06-24T00:00:00.000Z",
    "allDay": true
  },
  {
    "physicalId": 4299,
    "closedDate": "2017-06-25T00:00:00.000Z",
    "allDay": true
  }
]

我使用lodash v4.17.4以如下方式汇总数据:

[
  {
    "Sat Jun 24 2017 00:00:00 GMT+0000": 2,
    "Sun Jun 25 2017 00:00:00 GMT+0000": 3,
  }
]

但是,我希望它以

格式作为对象返回
[
  {
    date: "Sat Jun 24 2017 00:00:00 GMT+0000"
    total: 2
  },
    {
    date: "Sun Jun 25 2017 00:00:00 GMT+0000"
    total: 3
  }
]

我还没有找到在Lotash中完成此操作的方法。如何实现此目标?


解决方案

您可以在_.countBy之后使用_.map

_.map(_.countBy(source, "closedDate"), (val, key) => ({ date: key, total: val }))

相关文章