我以为我用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
好。
您使用的是烬数据吗? –
@selvaraj:是的我是 – redOctober13
这个代码在哪里? – locks