5

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?

6
  • Have you tried to iterate over object properties and get their values Commented Apr 6, 2017 at 8:32
  • 2
    Don't use a for loop, merge or extend. Why not? It will be more dynamic. Commented Apr 6, 2017 at 8:33
  • user like Number(val1) + Number(val2) + Number(val3) this will be helpful Commented Apr 6, 2017 at 8:34
  • @lonut Seems that is a homework question, with this restrictions. Commented Apr 6, 2017 at 8:34
  • 1
    @MudassarZahid Why convert a number to a number? Commented Apr 6, 2017 at 8:35

7 Answers 7

11

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)

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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)

1 Comment

Pretty much the only way if they don't want to use a for loop or similar.
0

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

Comments

0

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, {}));

Comments

0

you can code it dynamically :

var resultObject={};
Object.keys(obj1).forEach(function(objectKey, index) {
    resultObject[objectKey]= obj1 [objectKey]+obj2[objectKey];

});

1 Comment

You should use Object.keys(obj1).foreach() instead of map because you're updating another object.
-2

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)

2 Comments

How is this different from prasad's answer?
You could have at least used different identifiers -_-

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.