How to use groupBy in Backbone.js to group collections?

纵饮孤独 提交于 2019-12-21 01:28:07

问题


An example collection (showing models only):

[
    {
        name: "Bob"
        date: "Thu Mar 29 2012"
    },
    {
        name: "James"
        date: "Fri Mar 30 2012"
    },
    {
        name: "Dylan"
        date: "Fri Mar 30 2012"
    },
    {
        name: "Stanley"
        date: "Sat Mar 31 2012"
    },
]

How can I use Underscore.js' groupBy function to group models with the same date?


回答1:


Use _.groupBy(data, 'date');

You could also use pass a custom function, but in this case it's not necessary as the attribute shortcut syntax above works fine.

_.groupBy(data, function(row) {
    return row.date;
});

Demo:

> _.groupBy(data, 'date')
{ 'Thu Mar 29 2012': [ { name: 'Bob', date: 'Thu Mar 29 2012' } ],
  'Fri Mar 30 2012':
   [ { name: 'James', date: 'Fri Mar 30 2012' },
     { name: 'Dylan', date: 'Fri Mar 30 2012' } ],
  'Sat Mar 31 2012': [ { name: 'Stanley', date: 'Sat Mar 31 2012' } ] }
> _.groupBy(data, function(row) { return row.date });
{ 'Thu Mar 29 2012': [ { name: 'Bob', date: 'Thu Mar 29 2012' } ],
  'Fri Mar 30 2012':
   [ { name: 'James', date: 'Fri Mar 30 2012' },
     { name: 'Dylan', date: 'Fri Mar 30 2012' } ],
  'Sat Mar 31 2012': [ { name: 'Stanley', date: 'Sat Mar 31 2012' } ] }
>



回答2:


If you are grouping an actual backbone collection you can use the backbone method groupBy which implicitly uses underscore _.groupBy functionality. This is a much cleaner approach in my opinion.

collection.groupBy( function(model){
  return model.get('date');
});



回答3:


ThiefMaster answer is perfectly valid, but it caused me some confusion because I was searching a solution for a backbone.js collection as the title indicates.

If the question object is a backbone collection we should do the following to group the models by date:

_.groupBy(collection.models, function(model){
    return model.get('date')
});

I hope it helps




回答4:


var groups =collection.groupBy(function(model) { return model.get('date'); });

//iterate over groups
for(date in groups) { 
    var models = groups[date];
    console.log('date: '+date); 
    for (var model_idx in models) {  
        console.log('    name: '+ models[model_idx].get('name'));
    }
}



回答5:


For those using Lodash instead of underscore, you can achieve the same result using the _.method() accessor,

collection.groupBy(_.method('get', 'date'));


来源:https://stackoverflow.com/questions/9954597/how-to-use-groupby-in-backbone-js-to-group-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!