我有一个数据源如下
[
{
"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
}
]
我无法在lodash中找到完成此操作的方法。我怎样才能做到这一点?
答案 0 :(得分:1)
您可以在_.map
之后使用_.countBy
:
_.map(_.countBy(source, "closedDate"), (val, key) => ({ date: key, total: val }))
答案 1 :(得分:1)
我不确定,但我认为this mapkey function会有所帮助
答案 2 :(得分:0)
使用普通的js,以下两个reduce()会将原始数据转换为所需的格式:
let d = [{
"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
}
];
let r = [
...d.reduce((a, b) => {
a.set(b.closedDate, a.has(b.closedDate) ? a.get(b.closedDate) + 1 : 1);
return a;
}, new Map)
].reduce((a, b) => {
let [date, total] = [...b];
return a.concat({date, total});
}, []);
console.log(r);

答案 3 :(得分:0)
我们在这里使用ES6语法,使用.reduce()
和.find()
数组助手。
我们还使用ES6 spread operator来更改对象中的现有数据。
这是工作示例。
var data = [
{
"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
}
]
const newData = data.reduce((previous, current) => {
const recordExists = previous.find(record => record.date === current.closedDate);
if (!recordExists) {
return previous = [ ...previous, { date: current.closedDate, total: 1 } ];
}
recordExists.total += 1;
return [ ...previous, recordExists ];
}, []);
console.log(newData);