I would like to merge two objects together. Numbers should not be replaced, but added.
If I use the spread operator, numbers are replaced.
How it works for the moment:
let obj1 = { title: 'Number', num: 1 }
let obj2 = { title: 'Number', num: 2 }
let merge = { ...obj1, ...obj2 }
// Object { title: 'Number', num: 2 }
How it should work:
let obj1 = { title: 'Number', num: 1 }
let obj2 = { title: 'Number', num: 2 }
let merge = { ...obj1, ...obj2 }
// Object { title: 'Number', num: 3 }
In the end the number should be added to each other instead of being replaced. Is this possible with the spreach syntax?
You should be able to get the sum easily enough using Array.reduce(), we create an array containing the objects to be merged, then reduce to get the result:
let obj1 = { title: 'Number', num: 1 }
let obj2 = { title: 'Number', num: 2 }
let a = [obj1, obj2];
const result = a.reduce ((acc, cur) => {
return { ...cur, num: (acc.num || 0) + cur.num};
}, {});
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You also can try something like this
let obj1 = { title: 'Number', num: 1 }
let obj2 = { title: 'Number', num: 2 }
const obj = {};
obj['title'] = obj1['title']
obj['num'] = obj1['num'] + obj2['num']
console.log(obj)