Better way to sum a property value in an array

后端 未结 16 1487
遥遥无期
遥遥无期 2020-11-22 02:41

I have something like this:

$scope.traveler = [
            {  description: \'Senior\', Amount: 50},
            {  description: \'Senior\', Amount: 50},
             


        
16条回答
  •  后悔当初
    2020-11-22 03:25

    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! :)

提交回复
热议问题