Sum all properties in object

后端 未结 8 1818
礼貌的吻别
礼貌的吻别 2021-01-15 03:38

I have the following object:

{\"speed\":299,\"equipment\":49,\"teleabb\":49,\"additional\":50,\"optional\":\"299\"}

I want to sum all this

相关标签:
8条回答
  • 2021-01-15 04:04

    My for-less version:

    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    
    function sumProperties(obj) {
       return Object.getOwnPropertyNames(obj)
       .map(function(item){ return +obj[item];})
       .reduce(function(acc,item) { return acc + item; });
    }
    
    document.write(sumProperties(obj));

    0 讨论(0)
  • 2021-01-15 04:05

    Using Lodash:

    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    
    var val = _.sumBy(_.values(obj), function(v) {
       return parseInt(v)
    });
    

    Example: https://codepen.io/dieterich/pen/dyymoxM?editors=0012

    0 讨论(0)
  • 2021-01-15 04:08
    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    
    
    function sum(obj){
        var sum = 0;
        for(var key in obj){
          if (obj. hasOwnProperty(key)) {
              sum += parseInt(obj[key]) || 0;  
           }
        }
        return sum
    }
    
    console.log(sum(obj));
    

    parseInt(obj[key]) || 0; is important id the value is not a number

    0 讨论(0)
  • 2021-01-15 04:10
    1. Iterate over the object properties using for(var in)
    2. Use parseInt since some of the integers are in string form

    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    var sum = 0;
    
    for(var key in obj){
      sum += parseInt(obj[key]);
      }
    
    document.write(sum);

    0 讨论(0)
  • 2021-01-15 04:18

    Given

    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional": 299}
    

    you can do it very easily with the lodash library:

    var result = _.sum(obj);
    

    If some of your values aren't numbers, you need to map them to numbers first:

    var result = _.sum(_.map(obj, function(n){
         return +n;
         //or parseInt(n) or parseInt(n,10)
    }));
    

    http://plnkr.co/edit/UQs1aTCJ8qe1kG15G4x7?p=preview

    0 讨论(0)
  • 2021-01-15 04:18
    var sum = 0;
    for(var key in objects) {
        sum += parseInt(objects[key]);
    }
    console.log(sum);
    
    0 讨论(0)
提交回复
热议问题