Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
Object recursive merge in ES6 vanilla Javascript

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!