JSFiddle - React, Tailwind, and code Playground
JavaScript
var sales = {
obs1:{
Sales1:{
Region:"North", Value: 200, OtherValue: 12},
Sales2:{
Region:"South", Value:100, OtherValue: 15}},
obs2:{
Sales1:{
Region:"North", Value: 50, OtherValue: 18},
Sales2:{
Region:"South", Value:20, OtherValue: 20}}
};
var sales2 = {
a: {
obs1:{
Sales1:{
Region:"North", Value: 200, OtherValue: 12},
Sales2:{
Region:"South", Value:100, OtherValue: 15}}},
b: {
obs2:{
Sales1:{
Region:"North", Value: 50, OtherValue: 18},
Sales2:{
Region:"South", Value:20, OtherValue: 20}}
}
};
function sumUp(obj, propName, groupPropName, totals) {
var totals = totals || {};
for (var prop in obj) {
if (prop === propName) {
if (!totals[obj[groupPropName]]) {
totals[obj[groupPropName]] = 0
}
totals[obj[groupPropName]] += obj[propName]
} else if (typeof obj[prop] == 'object'){
sumUp(obj[prop], propName, groupPropName, totals);
}
}
return totals;
}
console.log (sumUp(sales, 'Value', 'Region'));
console.log (sumUp(sales, 'OtherValue', 'Region'));
console.log (sumUp(sales2, 'Value', 'Region'));
console.log (sumUp(sales2, 'OtherValue', 'Region'));