How to group by object by date?

非 Y 不嫁゛ 提交于 2020-05-08 09:49:09

问题


I fetching data form database and I want to send response date wise.

I want little bit of help in group By my data with date wise.

I have Object like as below

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"
  }];

I want like as below

  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"
     }]
  }];

I am using nodejs, moment, lo-dash. Please help me out of this.


回答1:


The usual solution to these questions is to group and map:

// 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();


来源:https://stackoverflow.com/questions/45455840/how-to-group-by-object-by-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!