Reputation: 121
I have a complex javascript object.
var obj = {foo: {bar: {baz1 : {price: 200},baz2: {price: 300}}};
How can I get the sum of price properties in it? Thanks
Upvotes: 0
Views: 219
Reputation: 6558
Here is another function with recursion to do it. For details check the code of getPriceSum()
function - the magic is done with reduce method and recursive calls.
var obj = {
foo: {
bar: {
baz1: {
price: 200
},
baz2: {
price: 300
}
}
}
};
var priceSum = getPriceSum(obj);
console.log('Sum of prices is ' + priceSum);
var obj = {
foo: {
price: 100,
bar: {
baz1: {
price: 200
},
baz2: {
price: 300
},
baz3: {
price: 250
},
}
}
};
var priceSum = getPriceSum(obj);
console.log('Another test - prices is ' + priceSum);
function getPriceSum(obj) {
var sum = Object.keys(obj).reduce(function(sum, prop) {
if(typeof obj[prop] === 'object'){
return sum + getPriceSum(obj[prop]);
}
if(prop === 'price'){
return sum + obj[prop];
}
}, 0);
return sum;
}
Upvotes: 0
Reputation: 386868
You could use a two step approach by finding all values with the given property name and then aggregate this values.
function getValues(object, key) {
return Object.keys(object).reduce(function (r, k) {
if (object[k] && typeof object[k] === 'object') {
return r.concat(getValues(object[k], key));
}
if (k === key) {
r.push(object[k]);
}
return r;
}, []);
}
var object = { foo: { bar: { baz1: { price: 200 }, baz2: { price: 300 } } } },
result = getValues(object, 'price').reduce((a, b) => a + b);
console.log(result);
Upvotes: 0
Reputation: 1199
You can try recursive function to look into each of the property.
var sum = 0;
function recursive(obj) {
$.each(obj, function(key, value) {
if (typeof value === "object") { //is it an object?
recursive(value);
} else {
sum += parseFloat(value); //if value is string, this will be 0
}
}
}
Upvotes: 0
Reputation: 1031
jQuery
var sum = 0
$.each(obj.foo.bar, function(index, value) {
sum += value.price
});
console.log(sum)
Javascript only:
var sum = 0
Object.keys(obj.foo.bar).map(function(objectKey, index) {
var value = obj.foo.bar[objectKey];
sum += value.price
});
console.log(sum)
Upvotes: 0
Reputation: 6311
try this
var sum = 0;
for(var i in obj.foo.bar){
sum += obj.foo.bar[i].price;
}
console.log(sum);
Upvotes: 2