Naim Mustafa
Naim Mustafa

Reputation: 344

How to merge and get sum of the values two objects has same keys as objects

I have two object that needs to be flattened for a chart implementation.

2019-09-12: {
        type1: {
            subType1: {
                   value: 5
                      },
            subType2: {…}               
                },
        type2: {
             subType1: {
                   value: 8
                      },
            subType2: {…} 
               }
        }

this needs to turn into this;

cumulated: {
        subType1: {
               value: 13
                  },
        subType2: {sum}               
            }

Upvotes: 2

Views: 569

Answers (4)

Naim Mustafa
Naim Mustafa

Reputation: 344

Thank you everybody! Here is what I ve come up with at the end:

I have used lodash library but its realy fast and clean. Also shape of the object is not important it can go as deep as your object goes

import mergeWith from 'lodash/mergeWith'

mergeWith({}, ...Object.values(objectThatNeedsToCollapse), (objValue, srcValue) =>
typeof objValue === "number" ? objValue + srcValue : undefined
)

Upvotes: 0

ChrisG
ChrisG

Reputation: 2948

You can iterate over the keys of the object and sum them.

const obj = {
  type1: {
    subType1: {
      value: 5
    },
    subType2: {
      value: 1
    },
  },
  type2: {
    subType1: {
      value: 8
    },
    subType2: {
      value: 2
    }
  }
};

const combine = (obj) => Object.keys(obj).reduce((res, cur) => {
    for (let key of Object.keys(obj[cur])) {
      if (res.hasOwnProperty(key)) {
        res[key].value += obj[cur][key].value;
      } else {
        res[key] = obj[cur][key];
      }
    };
    return res;
}, {});

console.log(combine(obj));

Upvotes: 1

medou boushab
medou boushab

Reputation: 66

    var obj = {"2019-09-12": {
        type1: {
            subType1: {
                   value: 5
                      },
            subType2: {value: 7}               
                },
        type2: {
             subType1: {
                   value: 8
                      },
            subType2: {value: 9} 
               }
        }}
var sumType1 = 0;
var sumType2 = 0;
function cumul(){
  Object.keys(obj).forEach(function(date){
  Object.keys(obj[date]).forEach(function(typeValue){
    sumType1 += obj[date][typeValue].subType1.value;
    sumType2 += obj[date][typeValue].subType2.value;
  })
})
return {
  cumulated: {
        subType1: {
               value: sumType1
                  },
        subType2: {sumType2}               
            }
}
}

console.log(cumul())

Upvotes: 1

jad
jad

Reputation: 138

You can use lodash library. For example

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

Upvotes: 1

Related Questions