How to group Ember data records?

2.8k views Asked by At

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?

2

There are 2 answers

0
Kalman On BEST ANSWER

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.[]')
0
real_ate On

I've just come across this answer and have a lot of success with using the ember-group-by addon.

The groupedResults example above written with the addon would look like this:

import Controller from '@ember/controller';
import groupBy from 'ember-group-by';

export default Controller.extend({
  groupedResults: groupBy('model', 'type')
});

This is the more modern way to define "properties" (computed properties) and is nice and clean