ember-dataember-cliember-1

How to group Ember data records?


I have a route that looks like this:

model: function() {
  return Ember.RSVP.hash({
    orders: this.store.find('order')
  });
},

Which returns all orders. An order has the following fields: id, user_id and product_id.

My API returns:

[
    { id: 1, user_id: 1, product_id:1 },
    { id: 2, user_id: 1, product_id:1 },
    { id: 3, user_id: 1, product_id:2 }
]

Which translates to, the same user has 3 orders. 2 apples (which cost $1 each) and an orange (which costs $1).

In my .hbs template. I'd like to display something along the lines of:

2 apples: $2
1 orange: $1

How do I go about grouping orders? Unfortunately, the Ember.Enumerable class (http://emberjs.com/api/classes/Ember.Enumerable.html) goes as far as sortBy. No groupBy.

Should I be looking at reduce or something else?


Solution

  • Check out the following discussion - http://discuss.emberjs.com/t/ember-enumerable-no-group-by/3594

    Basically, you would do something like

    groupedResults: function () {
      var result = [];
    
      this.get('content').forEach(function(item) {
        var hasType = result.findBy('type', item.get('type'));
    
        if(!hasType) {
         result.pushObject(Ember.Object.create({
            type: item.get('type'),
            contents: []
         }));
        }
    
        result.findBy('type', item.get('type')).get('contents').pushObject(item);
       });
    
       return result;
    }.property('content.[]')