我有以下对象:
{"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"}
我想将所有这些值相加并打印出来。如何求和属性值? :)
答案 0 :(得分:8)
firstp
box-sizing: border-box
,因为某些整数是字符串形式
, 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.keys和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
答案 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)
}));
答案 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)
});