2

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?

JeanValjean
  • 17,172
  • 23
  • 113
  • 157
  • 1
    this? https://stackoverflow.com/a/56256929/13583510 – cmgchess Aug 02 '22 at 20:59
  • I think so. So the answer is: no native approach, you have to implement your algorithm. – JeanValjean Aug 02 '22 at 21:00
  • What would your desired output be? – Joel Aug 02 '22 at 21:19
  • An approach like: `const merged = Object.assign({}, foo, { propB: bar.propB, BarPropShared: bar.propShared, });` would probably be the easiest and most painless given the information I have. – Joel Aug 02 '22 at 21:23
  • @Joel as soon as you know the properties of the object that's the best. Unfortunately it is not my case. I receive a structured group of options (not flat, unfortunately) that I have to merge with another. I'm always concerned with efficiency and I think that native approaches are always the best, but I suspect that I have to implement my own solution or mimic an existing _ad hoc_ implementation like the one reported above by cmgchess – JeanValjean Aug 03 '22 at 06:30

0 Answers0