求和对象中的所有属性

时间:2015-06-10 12:48:42

标签: javascript arrays

我有以下对象:

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

我想将所有这些值相加并打印出来。如何求和属性值? :)

8 个答案:

答案 0 :(得分:8)

  1. 使用firstp
  2. 迭代对象属性
  3. 使用box-sizing: border-box,因为某些整数是字符串形式
  4.     , CONVERT( nvarchar(20), CAST(CONVERT(nvarchar(10), GETDATE(), 112) AS decimal(20,0)) * POWER( 10,8) + ROW_NUMBER() OVER (order by id))
    

答案 1 :(得分:3)

以下是使用ES5&{39} Object.keysreduce进行此操作的方法:

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

答案 2 :(得分:1)

我的永久版本:



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));




答案 3 :(得分:1)

给出

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

您可以使用lodash库轻松完成:

var result = _.sum(obj);

如果您的某些值不是数字,则需要先将它们映射到数字:

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

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

答案 4 :(得分:0)

var sum = 0;
for(var key in objects) {
    sum += parseInt(objects[key]);
}
console.log(sum);

答案 5 :(得分:0)

你可以这样做:

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/

答案 6 :(得分:0)

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;是重要的ID,值不是数字

答案 7 :(得分:0)

使用Lodash:

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

var val = _.sumBy(_.values(obj), function(v) {
   return parseInt(v)
});

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