LeBlaireau
LeBlaireau

Reputation: 17467

Javascript (Vuejs) object literal, looping

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

Answers (1)

str
str

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 keys
  • map returns an array of the amounts
  • reduce sums up all the amounts

Don't forget to use Babel or Traceur for transpiling to ES5.

Upvotes: 4

Related Questions