How to sum two object values in javascript

后端 未结 7 592
长发绾君心
长发绾君心 2021-01-13 18:25

I\'m stuck how i sum two object like this:

obj1 = { 
  \'over_due_data\': 10,
  \'text_data\': 5
} 

obj2 = {
  \'over_due_data\': 20,
  \'text_data\': 5
}
<         


        
相关标签:
7条回答
  • 2021-01-13 19:18

    This question already have a lot of goods answers but I make a version who also handle multi-levels objects:

    let sumAllKeys = (obj1, obj2) => Object.keys({...obj1, ...obj2}).reduce((acc, key) => {
      let key1 = obj1 && obj1[key] || 0;
      let key2 = obj2 && obj2[key] || 0;
      acc[key] = (typeof key1 == "object" || typeof key2 == "object")
        ? sumAllKeys(key1, key2)
        : (parseFloat(key1) || 0) + (parseFloat(key2) || 0);
      return acc;
    }, {});
    
    
    // Example: 
    
    let a = {qwerty:1, azerty: {foo:2, bar:3}}
    let b = {qwerty:5, azerty: {foo:4}, test:{yes:12, no:13}};
    let c = {azerty: {bar:2}, test:{no:1}, another:{child:{subchild:3}}};
    
    console.log("Sum of: ", {a,b,c});
    console.log("Equal: ", [a, b, c].reduce(sumAllKeys, {}));

    0 讨论(0)
提交回复
热议问题