Reputation: 17467
I have an object in vuejs
data: {
food: {
monday: {
pizza:1,
chips:2,
pie:0,
},
tuesday: {
pizza:1,
chips:2,
pie:1,
}
}
}
I can access the value specifically with
this.food.monday.pizza
but how do I count the number of items eaten on monday (3 total)?
Upvotes: 0
Views: 1024
Reputation: 44969
In ES6 you can do it as follows.
const objectValueSum = (obj) =>
Object.keys(obj)
.map(food => obj[food])
.reduce((a, b) => a + b);
const sum = objectValueSum(this.data.food.monday);
Object.keys
returns the object keysmap
returns an array of the amountsreduce
sums up all the amountsDon't forget to use Babel or Traceur for transpiling to ES5.
Upvotes: 4