使用下划线,我已经成功地实现了按多个属性对对象进行分组和对组求和的逻辑,但是我还没有找到使用lodash进行分组的方法。
代码如下:
let test = _.chain(response.counterValues)
.flatten()
.groupBy(response.counterValues, (item) => {
return item.duration + '#' + item.timeFrom + '#' + item.timeTo + '#' + item.objectClass;
})
.mapValues((value, key) => {
let sum = _.reduce(value, (memo, val) => {return memo + val.count}, 0);
let keyItems = key.split('#');
let duration = keyItems[0];
let timeFrom = keyItems[1];
let timeTo = keyItems[2];
let objectClass = keyItems[3];
return {duration: duration, timeFrom: timeFrom, timeTo: timeTo, objectClass: objectClass, count: sum};
}).value();
console.log(test);
这些是示例值:
0: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 1}
1: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 3}
2: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 1}
3: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 1}
4: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 3}
5: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 2}
6: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 1}
7: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 2}
8: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 4}
9: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 1}
10: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 2}
11: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 2}
12: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 2}
13: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 3}
14: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 2}
15: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 1}
16: {duration: "h", timeFrom: "1547323200000", timeTo: "1547326800000", objectClass: "car", count: 1}
对于这些对象,我希望得到以下结果:
{duration: "h", timeFrom: 1547323200000, timeTo: 1547326800000, objectClass: "car", count: 32}
是否有人知道如何修改上述代码以获得所需的结果?