Sum all properties in object

后端 未结 8 1898
礼貌的吻别
礼貌的吻别 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: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

提交回复
热议问题