Reputation: 2523
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
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
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);
})
Upvotes: 2
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;
})
Upvotes: 3