Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum two object values in javascript

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
}

I went this output

obj = {
  'over_due_data': 30,
  'text_data': 10
}

One more thing, don't use a for loop, merge and extend. Is it possible to sum two objects?

like image 618
skvj Avatar asked Apr 06 '17 08:04

skvj


2 Answers

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)
like image 55
prasanth Avatar answered Oct 04 '22 03:10

prasanth


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);
like image 34
kind user Avatar answered Oct 04 '22 04:10

kind user