简体   繁体   English

如何合并并获取两个对象的值之和与对象具有相同的键

[英]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}               
            }

You can use lodash library . 您可以使用lodash库 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 }] }
    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())

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));

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. 我使用过lodash库,但它的确快速又干净。 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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM