如何在javascript中按对象日期分组?

时间:2017-08-02 08:45:13

标签: node.js momentjs lodash

我从数据库中获取数据,我希望明智地发送响应日期。

我希望在小组中提供一些帮助我的数据与日期明智。

我有像下面的对象

var IHAVE =   [{
      "foodId": "59031fdcd78c55b7ffda17fc",
      "qty": 1,
      "dateTime": "2017-07-26T12:03:06.000Z",
      "_id": "591c3bfcca93e86c3450a537"
  }, {
      "foodId": "59031fdcd78c55b7ffda17fc",
      "qty": 1,
      "dateTime": "2017-05-18T04:21:13.000Z",
      "_id": "591d213b6878badb0621b840"
  }, {
      "foodId": "59031fdcd78c55b7ffda17fc",
      "qty": 1,
      "dateTime": "2017-07-26T12:03:010.000Z",
      "_id": "591c3bfcca93e86c3450a537"
  },{
      "foodId": "59031fdcd78c55b7ffda17fc",
      "qty": 1,
      "dateTime": "2017-05-18T04:22:01.000Z",
      "_id": "591d216a6878badb0621b842"
  }];

我想要如下

  var IWANT = [{ 
     date: "2017-07-26",
     data: [{
       "foodId": "59031fdcd78c55b7ffda17fc",
       "qty": 1,
       "dateTime": "2017-07-26T12:03:06.000Z",
       "_id": "591c3bfcca93e86c3450a537"
     },{
       "foodId": "59031fdcd78c55b7ffda17fc",
       "qty": 1,
       "dateTime": "2017-07-26T12:03:010.000Z",
       "_id": "591c3bfcca93e86c3450a537"
     }]
  }, {
     date: "2017-05-18",
     data: [{
       "foodId": "59031fdcd78c55b7ffda17fc",
       "qty": 1,
       "dateTime": "2017-05-18T04:21:13.000Z",
       "_id": "591d213b6878badb0621b840"
     },{
       "foodId": "59031fdcd78c55b7ffda17fc",
       "qty": 1,
       "dateTime": "2017-05-18T04:22:01.000Z",
       "_id": "591d216a6878badb0621b842"
     }]
  }];

我正在使用nodejs,moment,lo-dash。 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

这些问题的常用解决方案是groupmap

// Helper function to extract the date from a dateTime
var date = function(d){
    return moment(d.dateTime).format('YYYY-MM-DD');
}

// map a group to the required form
var groupToSummary = function(group, date) {
    return {
        date: date,
        data: group
    }
}

var IWANT = _(IHAVE)
    .groupBy(date)
    .map(groupToSummary)
    .value();