I have something like this:
$scope.traveler = [
{ description: \'Senior\', Amount: 50},
{ description: \'Senior\', Amount: 50},
I thought I'd drop my two cents on this: this is one of those operations that should always be purely functional, not relying on any external variables. A few already gave a good answer, using reduce
is the way to go here.
Since most of us can already afford to use ES2015 syntax, here's my proposition:
const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);
We're making it an immutable function while we're at it. What reduce
is doing here is simply this:
Start with a value of 0
for the accumulator, and add the value of the current looped item to it.
Yay for functional programming and ES2015! :)