-
牛魔王的故事
您可以遍历对象的键并对它们求和。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));
-
12345678_0001
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())
-
守着星空守着你
您可以使用lodash 库。例如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 }] }