How do I group Ember data records?

I have a route that looks like this:

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

      

Returns all orders. The procedure 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 means the same user has 3 orders. 2 apples (which cost $ 1) and an orange (which costs $ 1).

In my template .hbs

. I would like to show something along the lines:

2 apples: $2
1 orange: $1

      

How can I organize order grouping? Unfortunately the Ember.Enumerable class ( http://emberjs.com/api/classes/Ember.Enumerable.html ) comes down to sortBy

. No groupBy

.

Should I watch reduce

or something else?

+3


source to share


1 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.[]')

      

+2


source







All Articles