Search code examples
javascriptecmascript-6ecmascript-2016

Is there an easy way to merge objects and sum their int properties instead of overriding in javascript es2018?


Alright, so this is what I have in mind.

I have two example objects

let obj1 = { x: 60 };

let obj2 = { x: 9 };

I want to merge these objects in a way that their integer properties will combine as well, and not override each other, so the end result will be

let obj3 = { x: 69 };

So I've looked into Object.assign, but this function only merges properties in a way that it favors the properties on the first object if the other objects have a property with the same name, and doesn't sum integer properties.

I can, of course, just make a function that loops over each object's properties and creates a new object with the summed properties, but that'd be longer and I wanted to know if there's already a function that does it easily like the way Object.assign acts.

Thank you.


Solution

  • If you want to use Lodash library you could do this with mergeWith method.

    let obj1 = { x: 60, b: "foo", c: {y: 3, x: 'bar'} };
    let obj2 = { x: 9, a: 'bar', c: {y: 4} };
    
    const sum = _.mergeWith(obj1, obj2, (a, b) => {
      if (_.every([a, b], _.isNumber)) return a + b;
    })
    
    console.log(sum)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>