How to sum the values of a JavaScript object?

后端 未结 14 790
梦如初夏
梦如初夏 2020-11-27 04:03

I\'d like to sum the values of an object.

I\'m used to python where it would just be:

sample = { \'a\': 1 , \'b\': 2 , \'c\':3 };
summed =  sum(sampl         


        
14条回答
  •  爱一瞬间的悲伤
    2020-11-27 04:24

    Honestly, given our "modern times" I'd go with a functional programming approach whenever possible, like so:

    const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);
    

    Our accumulator acc, starting with a value of 0, is accumulating all looped values of our object. This has the added benefit of not depending on any internal or external variables; it's a constant function so it won't be accidentally overwritten... win for ES2015!

提交回复
热议问题