How to sum two object values in javascript

后端 未结 7 591
长发绾君心
长发绾君心 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:05

    you can code it dynamically :

    var resultObject={};
    Object.keys(obj1).forEach(function(objectKey, index) {
        resultObject[objectKey]= obj1 [objectKey]+obj2[objectKey];
    
    });
    
    0 讨论(0)
  • 2021-01-13 19:07

    Another possible solution, using Array#reduce.

    var obj1 = {'over_due_data':10,'text_data':5}, obj2 = {'over_due_data':20,'text_data':5},
        obj = Object.keys(obj1).reduce(function(s,a) {
          s[a] = obj1[a] + obj2[a];
          return s;
        }, {})
        console.log(obj);

    0 讨论(0)
  • 2021-01-13 19:09

    try with simply use Object.keys() and Array#map() function

    obj1 = {
      'over_due_data': 10,
      'text_data': 5
    }
    obj2 = {
      'over_due_data': 20,
      'text_data': 5
    }
    var obj ={}
    Object.keys(obj1).forEach(function(a){
      obj[a] = obj1[a] +obj2[a]
    
    })
    console.log(obj)

    0 讨论(0)
  • 2021-01-13 19:11

    Try something like this if you don't want to use loop

        obj1 = { 
          'over_due_data': 10,
          'text_data': 5
        } 
        
        obj2 = {
          'over_due_data': 20,
          'text_data': 5
        }
        var obj = {};
        obj['over_due_data'] = obj1['over_due_data'] + obj2['over_due_data']
        obj['text_data'] = obj1['text_data'] + obj2['text_data']
    
        console.log(obj)

    0 讨论(0)
  • 2021-01-13 19:13

    Try this might be helpful

    obj1 = {
      'over_due_data': 10,
      'text_data': 5
    }
    obj2 = {
      'over_due_data': 20,
      'text_data': 5
    }
    var obj ={}
    Object.keys(obj1).map(function(a){
      obj[a] = obj1[a] +obj2[a]
    
    })
    console.log(obj)

    0 讨论(0)
  • 2021-01-13 19:18

    I have used below snippet to sum the two objects even if any of them has additional properties.

    This solution is based on Array.prototype.reduce and short-circuit evaluation

    Object.keys({ ...obj1, ...obj2 }).reduce((accumulator, currentValue) => {
        accumulator[currentValue] =
            (obj1[currentValue] || 0) + (obj2[currentValue] || 0);
        return accumulator;
    }, {});
    

    var obj1 = {
      'over_due_data': 10,
      'text_data': 5,
      'some_add_prop': 80
    };
    
    var obj2 = {
      'over_due_data': 20,
      'text_data': 5,
      'add_prop': 100
    };
    
    
    const sumOfObjs = Object.keys({ ...obj1,
      ...obj2
    }).reduce((accumulator, currentValue) => {
      accumulator[currentValue] =
        (obj1[currentValue] || 0) + (obj2[currentValue] || 0);
      return accumulator;
    }, {});
    
    console.log(sumOfObjs);

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