使用_.js将对象值聚合到新对象中

时间:2014-03-06 20:42:53

标签: javascript underscore.js

假设我有一个数组

var i = [{event: 'create', date: '03/11'}, {event: 'delete', date: '03/11'}, {event: 'put', date: '05/11'}, {event: 'delete', date: '06/11'}]

然后将它们缩减成一个对象:

var reduced = {03/11: 2, 05/11: 1, 06/11: 1}

使用会生成对象的_.js聚合这些结果的最佳方法是什么:

result = {03/11: [{event: 'create', date: '03/11'}, {event: 'delete', date: '03/11'}],
05/11: [{event: 'put', date: '05/11'}], 06/11: [{event: 'delete', date: '06/11'}]}

非常感谢任何帮助

1 个答案:

答案 0 :(得分:2)

这是_.groupBy的基本用例。

var i = [{event: 'create', date: '03/11'}, {event: 'delete', date: '03/11'}, {event: 'put', date: '05/11'}, {event: 'delete', date: '06/11'}];

var result = _.groupBy(i, function(item) {
    return item.date;
});

Fiddle