[Vuejs]-Javascript (Vuejs) object literal, looping

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.

👤str

Leave a comment