How to sum the values of a JavaScript object?

后端 未结 14 685
梦如初夏
梦如初夏 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:31

    Now you can make use of reduce function and get the sum.

    const object1 = { 'a': 1 , 'b': 2 , 'c':3 }
    
    console.log(Object.values(object1).reduce((a, b) => a + b, 0));

    0 讨论(0)
  • 2020-11-27 04:34

    Sum the object key value by parse Integer. Converting string format to integer and summing the values

    var obj = {
      pay: 22
    };
    obj.pay;
    console.log(obj.pay);
    var x = parseInt(obj.pay);
    console.log(x + 20);

    0 讨论(0)
提交回复
热议问题