0

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)?

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Objects.keys, map and reduce are functions from ES5, only the arrow notation is from ES6 in your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.