Sum All Properties In Object
I have the following object: {'speed':299,'equipment':49,'teleabb':49,'additional':50,'optional':'299'} I want to sum all this values and print It out. How can I sum the propertie
Solution 1:
- Iterate over the object properties using
for(var in)
- 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);
Solution 2:
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
Solution 3:
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));
Solution 4:
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)
}));
Solution 5:
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/
Post a Comment for "Sum All Properties In Object"