2016-05-13 70 views
2

我以爲我用reduce()計算出了這個數字,但其實我需要在每條記錄上彙總多個屬性,所以每當我返回一個對象時,我遇到的問題是previousValue是一個Ember對象,並且我返回一個普通對象,所以它在第一個循環中工作正常,但第二次通過,a不再是Ember對象,所以我得到一個錯誤說a.get is not a function。示例代碼:Ember.js:將模型記錄彙總成一條記錄

/* 
filter the model to get only one food category, which is determined by the user selecting a choice that sets the property: theCategory 
*/ 
var foodByCategory = get(this, 'model').filter(function(rec) { 
    return get(rec, 'category') === theCategory; 
}); 

/* 
Now, roll up all the food records to get a total 
of all cost, salePrice, and weight 
*/ 
summary = foodByCategory.reduce(function(a,b){ 
    return { 
    cost: a.get('cost') + b.get('cost'), 
    salePrice: a.get('salePrice') + b.get('salePrice'), 
    weight: a.get('weight') + b.get('weight') 
    }; 
}); 

我對這一切都錯了嗎?有沒有更好的方法將model中的多條記錄彙總到一條記錄中,還是隻需要將模型記錄平鋪爲簡單對象,或者返回reduce()中的Ember對象?

編輯:return Ember.Object.create({...})的工作,但我仍想這是否是實現這一目標的最佳途徑,或者一些意見,如果灰燼提供的功能,將做到這一點,如果是的話,如果他們比reduce好。

+0

您使用的是燼數據嗎? –

+0

@selvaraj:是的我是 – redOctober13

+0

這個代碼在哪裏? – locks

回答

0

假設this.get('model')返回Ember.Enumerable,您可以使用filterBy代替filter

var foodByCategory = get(this, 'model').filterBy('category', theCategory); 

至於你reduce,我不知道任何灰燼內置插件,將提高它的。我能想到的最好的是使用多個獨立mapByreduce電話:

summary = { 
    cost: foodByCategory.mapBy('cost').reduce(...), 
    salePrice: foodByCategory.mapBy('salePrice').reduce(...), 
    ... 
}; 

但是,這可能不太高性能。我不會太擔心使用Ember內置程序來執行標準數據操作...我知道的大多數Ember項目仍然使用實用程序庫(如Lodash)和Ember本身,通常在編寫此類代碼時效率更高的數據轉換。

+0

謝謝。我很滿意它是簡單的JavaScript來彙總數據。在你看來,減少()是最好的方法嗎?實質上,我試圖用一條記錄創建一個新模型。我還根據彙總屬性在「summary」中添加了其他屬性。我應該在路線中做到這一點,按類別捲起來,然後在控制器中只是'filterBy'? – redOctober13

+0

@ redOctober13取決於你的意思是「最好的」。 '減少'絕對是一個很好的方法。我不確定我有足夠的上下文來說明什麼對你的情況最好,但是聽起來像「摘要」是應用程序中的頭等對象,即使它不是模型。我會考慮創建一個Summary類作爲'const Summary = Ember.Object.extend({...',所以你可以用更多的OO方式定義Computed Properties,然後你可以像'summary = Summary .create(foodByCategory.reduce(...))','reduce'返回一個POJO,讓我知道如果我的意見不清楚。 –

+0

@ redOctober13哦,別的:你可能會發現http://emberjs.com/api /#method_get('Ember.get(obj,key)')有用:它可以在POJO和'Ember.Object'上工作。 –