0

In my data array I have rows per person filled with a couple of number values like this:

  {
    name: 'John doe',
    monday: 29837,
    tuesday: 30753,
    wednesday: 28079,
    thursday: 27144,
    friday: 27016,
  },

I need to calculate the total value per week. The only way I manage to get this is by displaying em like: {{ props.row.monday + props.row.tuesday }} But I'm sure there is a way better way than this.

Justin Dekkers
  • 147
  • 1
  • 1
  • 10
  • You can [loop through properties](https://stackoverflow.com/q/8312459/4636715) of your object; and maybe can sum up [checking their types](https://stackoverflow.com/questions/8525899/how-to-check-if-a-javascript-number-is-a-real-valid-number) or if the keys end with `-day`. It depends on your exact possible structure and approach. – vahdet Mar 04 '19 at 09:25
  • Possible duplicate of [How to sum the values of a JavaScript object?](https://stackoverflow.com/questions/16449295/how-to-sum-the-values-of-a-javascript-object) – Najam Us Saqib Mar 04 '19 at 09:26

1 Answers1

0

You are looking for this (in JS ES6):

Object.values(yourObject).filter(item => typeof item === 'number').reduce((a,b) => a+b)

Explanation:

  • Object.values() selects all the values of your object
  • .filter() filters your values so only numbers remain
  • .reduce() loops through the array and adds all the members together

A good article on the ES6 stuff: https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d

Object.values explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

Imre_G
  • 2,468
  • 1
  • 17
  • 33
  • This fixes what was going to be my next issue (total amount of every person). I need this per person aswell. Anyway i can filter that out? – Justin Dekkers Mar 04 '19 at 10:45