问题
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