Ember.js Grouping Results

后端 未结 3 716
长发绾君心
长发绾君心 2021-02-04 18:49

I\'m trying to achieve a \"group by\" functionality in Ember.js and its proving more difficult than I originally thought.

[{date: \'2014-01-15T16:22:16-08:00\',          


        
3条回答
  •  旧巷少年郎
    2021-02-04 19:13

    Here is an implementation, made available on Array objects:

    var groupByMethod = Ember.Mixin.create({
      groupBy: function(key) {        
        var result = [];
        var object, value;
    
        this.forEach(function(item) {
          value = item.get ? item.get(key) : item[key];
          object = result.findProperty('value', value);
          if (!object) {
            object = {
              value: value,
              items: []
            };
            result.push(object);
          }
          return object.items.push(item);
        });
    
        return result.getEach('items');
      }
    });
    
    groupByMethod.apply(Array.prototype);
    

    Usage:

    > var posts = [{id: 1, author: 'John'}, {id:2, author: 'Paul'}, {id:4, author: 'Paul'}, {id:5, authour: 'Tom'}];
    
    > posts.groupBy('author')
    

    usage example

提交回复
热议问题