【问题标题】:Ember.js: Summarize model records into one recordEmber.js:将模型记录汇总为一条记录
【发布时间】:2016-05-13 15:02:26
【问题描述】:

我以为我已经用reduce() 解决了这个问题,但问题是我需要在每条记录上汇总多个属性,所以每次我返回一个对象时,我遇到的问题是@ 987654322@ 是一个 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 汇总到一个记录中,还是我只需要先将模型记录展平为普通对象,或者在reduce() 中返回一个 Ember 对象?

编辑: 执行 return Ember.Object.create({...}) 确实有效,但我仍然想了解这是否是实现目标的最佳方式,或者 Ember 是否提供了可以执行此操作的函数,以及是否所以,如果他们比 reduce 更好的话。

【问题讨论】:

  • 你在使用 ember 数据吗?
  • @locks: 在我的控制器中

标签: ember.js ember-data


【解决方案1】:

假设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 本身,这通常在编写这种类型时会更有效的数据转换。

【讨论】:

  • 谢谢。我可以使用纯 JavaScript 来汇总数据。在您看来,reduce() 是最好的方法吗?从本质上讲,我正在尝试用一条记录创建一个新模型。我还将根据汇总的属性向summary 添加其他属性。我是否应该在路由中执行此操作,在那里按类别汇总,然后在控制器中仅使用 filterBy?
  • @redOctober13 取决于您所说的“最佳”是什么意思。 reduce 绝对是一个好方法。我不确定我是否有足够的上下文来说明最适合您的情况,但听起来“摘要”是您应用程序中的一流对象,即使它不是模型。我会考虑将摘要“类”创建为const Summary = Ember.Object.extend({...,因此您可以在那里以更面向对象的方式定义计算属性。然后你可以做类似summary = Summary.create(foodByCategory.reduce(...)) 的事情,你的reduce 返回一个POJO。如果我的评论不清楚,请告诉我。
  • @redOctober13 哦,还有别的东西:你可能会发现 emberjs.com/api/#method_get (Ember.get(obj, key)) 很有用:它适用于 POJO 和 Ember.Objects。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 2019-02-18
  • 2021-02-16
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
相关资源
最近更新 更多