我以为我使用reduce()
弄明白了,但是我需要在每条记录上汇总多个属性,所以每次我返回一个对象时,我遇到的问题是previousValue
是一个Ember对象,我正在返回一个普通对象,所以它在第一个循环中工作正常,但是第二次,a
不再是Ember对象,所以我得到了错误说a.get is not a function
。示例代码:
/*
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
汇总到一个记录中,或者我只需要先将模型记录展平为普通对象,或者在{{1}中返回一个Ember对象}}?
编辑执行reduce()
确实有效,但我仍然想知道这是否是实现目标的最佳方式,或者如果Ember提供了可以执行此操作的功能,如果是的话,如果他们比return Ember.Object.create({...})
更好。
答案 0 :(得分:0)
假设this.get('model')
返回Ember.Enumerable
,您可以使用filterBy代替filter
:
var foodByCategory = get(this, 'model').filterBy('category', theCategory);
至于你的reduce
,我不知道任何可以改善它的Ember内置插件。我能想到的最好的方法是使用多个独立的mapBy
和reduce
来电:
summary = {
cost: foodByCategory.mapBy('cost').reduce(...),
salePrice: foodByCategory.mapBy('salePrice').reduce(...),
...
};
但这可能不那么高效。我不会太担心使用Ember内置函数来进行标准数据操作......我所知道的大多数Ember项目仍然使用实用程序库(如Lodash)和Ember本身,这通常在写作时更有效这种数据转换。