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

64
Views
Merge object with same keys

I have a custom javascript object similar to this:

const my_obj = {
  'foo1': {
    'bar1': '1',
    'bar2': '2',
    'bar3': '3',
  },
  'foo1': {
    'bar4': '4',
    'bar5': '5',
  },
  'foo2': {
    'bar1': '1',
    'bar2': '2',
  }
}

and I want to merge elements with the same key, so in this case the object would become:

const my_obj = {
  'foo1': {
    'bar1': '1',
    'bar2': '2',
    'bar3': '3',
    'bar4': '4',
    'bar5': '5',
  },
  'foo2': {
    'bar1': '1',
    'bar2': '2',
  }
}

Is there any way to do this easily?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you try to define an object with clashing keys the first is overriten by the second (at least in my attempts).

Considering you have instead two objects with same keys you can make two types of merge: shallow or deep.

If a shallow merge is sufficient, you can use Object.assign to do the job like the following, but iterating for each key:

obj3.foo1 = Object.assign({}, obj1.foo1, obj2.foo1);

For shallow copies, keep in mind that the references are maintained since Object.assign only copies the values as explained into the documentation which can be a problem for nested objects.

But if you need a deep merge it would be a little bit more tricky. The easiest way I guess is using a library like deepmerge-json:

const result = merge(obj1, obj2)

This will make a deep merge between the two objects creating a third one with no reference to the original ones.

The advantage of this approach is that the objects will be merged no matter how many levels they have.

about 4 years ago · Juan Pablo Isaza Report
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!