Object recursive merge in ES6 vanilla Javascript

Viewed 20

Javascript since ES6 offers the spread operator ... as a convenience to merge, among different structures, objects. If objects have a property with the same name, then the right-most object property overwrites the previous one. E.g.

    const foo = {
      propA: 'a',
      propShared: 'sharedFoo',
    }
    
    const bar = {
      propB: 'b',
      propShared: 'sharedBar',
    }
    
    const mergedObject = {
        ...foo,
        ...bar
    };
    
    console.log(mergedObject);

will print out

{
    propA: 'a',
    propB: 'b',
    propShared: 'sharedBar'
}

Now, let's say that I want to recursively apply this pattern to all the properties which may be of type object. E.g. you may have

    const foo = {
      propA: 'a',
      propShared: {
         propX: 'x',
         propShared: {
            prop1: 1
         }
      },
    }
    
    const bar = {
      propB: 'b',
      propShared: {
         propY: 'y',
         propShared: {
            prop2: 2
         }
      },
    }

Given the rule above, if I do:

const mergedObject = {
        ...foo,
        ...bar
    };

I will completely loose the content from foo.propShared and keep bar.propShared. So, assuming that the properties are unknown, the only approach that I see is to collect the properties of each object through Object.keys, add unique properties to a new Object to be returned, search for properties in common, recurse on the function to create a new Object to be assigned to that property.

Is there any native way to do it or should I write an iterative algorithm as the one I mentioned above? What should be the way to go?

0 Answers
Related