Search code examples
javascriptember.jsember-datacomputed-properties

Computed property that returns a sum of a property on each model


I have a cart model then has items in it that looks something like this

[
    {
        "item_id": 1,
        "item_name":"Item 1",
        "item_price": 500
    },
    {
        "item_id": 2,
        "item_name": "Item 2",
        "item_price": 230
    },
    {
        "item_id": 3,
        "item_name": "Item 3",
        "item_price": 150
    }
]

I need to sum up the item_price property to be able to display it and then pass it along to ember data or an ajax call to complete a purchase.

Not sure if I'm just not understanding the agregate data thing with computeds but I am trying with this

totalDue: Ember.computed.sum('model.@each.item_price')

On the controller but it's returning 0

I am on ember 2.2.0


Solution

  • You can also do this as a very clean one-liner:

    totalDue: Ember.computed('model.@each.item_price', function() {
      return this.get('model').mapBy('item_price').reduce((a, b) => a + b, 0);
    })
    

    Working Demo