2014-03-06 68 views
0

假設我有一個數組彙總對象的值到新的使用對象_.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'}]} 

任何幫助將不勝感激

回答

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