2014-12-19 54 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.[]')