Sum all properties in object

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

    Here's a way of doing it using ES5's Object.keys and reduce:

    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    var sum = Object.keys(obj).reduce(function(prev, current, index) {
        return prev + (+obj[current]);
    }, 0);
    console.log(sum); // 746

    jsFiddle

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

    You can do it this way:

    var sum_object = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    var sum = 0;
    
    for( var index in sum_object ){
        sum += parseInt(sum_object[index]);
        console.log("Val: ",sum_object[index], sum);
    };
    
    console.log(sum);
    

    JSFiddle: http://jsfiddle.net/abvuh5m0/

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