Jordan
Jordan

Reputation: 2523

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('[email protected]_price')

On the controller but it's returning 0

I am on ember 2.2.0

Upvotes: 1

Views: 1051

Answers (3)

joshuahornby10
joshuahornby10

Reputation: 4292

You could also do it like this:

export default Ember.Controller.extend({
      model: [
        {
          "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
        }
      ],

      array: Ember.computed.mapBy('model', 'item_price'),
      sum: Ember.computed.sum('array'),
    });

Upvotes: 1

jeffdill2
jeffdill2

Reputation: 4114

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

totalDue: Ember.computed('[email protected]_price', function() {
  return this.get('model').mapBy('item_price').reduce((a, b) => a + b, 0);
})

Working Demo

Upvotes: 2

Daniel
Daniel

Reputation: 18692

You can do it like this:

totalDue: Ember.computed('[email protected]_price', function() {
  const model = this.get('model');
  if (!model) {
    return 0;
  }

  let sum = 0;
  model.forEach(item => sum += Ember.get(item, 'item_price'));
  return sum;
})

Working demo.

Upvotes: 3

Related Questions