2016-05-13 74 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'上工作。 –