2014-12-19 84 views
3

我有一个看起来像这样的路线:如何将Ember数据记录分组?

model: function() { 
    return Ember.RSVP.hash({ 
    orders: this.store.find('order') 
    }); 
}, 

它返回所有订单。订单具有以下字段:id,user_idproduct_id

我的API收益:

[ 
    { id: 1, user_id: 1, product_id:1 }, 
    { id: 2, user_id: 1, product_id:1 }, 
    { id: 3, user_id: 1, product_id:2 } 
] 

翻译为,同一用户拥有3个数量级。 2个苹果(每个成本1美元)和一个橙色(成本1美元)。我的.hbs模板。我想展示一些内容:

2 apples: $2 
1 orange: $1 

我该如何进行分组订单?不幸的是,Ember.Enumerable类(http://emberjs.com/api/classes/Ember.Enumerable.html)远远达到sortBy。没有groupBy

我应该看reduce还是别的?

+0

我需要一个js小提琴:) – Sushant 2014-12-19 13:41:59

回答

2

看看下面的讨论 - http://discuss.emberjs.com/t/ember-enumerable-no-group-by/3594

基本上,你会做类似

groupedResults: function() { 
    var result = []; 

    this.get('content').forEach(function(item) { 
    var hasType = result.findBy('type', item.get('type')); 

    if(!hasType) { 
    result.pushObject(Ember.Object.create({ 
     type: item.get('type'), 
     contents: [] 
    })); 
    } 

    result.findBy('type', item.get('type')).get('contents').pushObject(item); 
    }); 

    return result; 
}.property('content.[]')