lodash键添加到countBy功能
问题描述:
我有一个数据源如下lodash键添加到countBy功能
[
{
"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
}
]
我还没有找到办法来完成这个我n lodash。我怎样才能做到这一点?
答
您可以使用_.map
后_.countBy
:
_.map(_.countBy(source, "closedDate"), (val, key) => ({ date: key, total: val }))
答
使用普通的js,下面的两个减少()将原始数据转化为所需的格式:
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);
答
我们在这里使用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);
我没有任何按键在原来的结果,我流汗引用。它的日期和号码 –
@ mcgowan.b查看我更新的答案 – Saravana