Laskii
Laskii

Reputation: 31

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?

Upvotes: 1

Views: 2840

Answers (1)

Kleber
Kleber

Reputation: 1065

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.

Upvotes: 0

Related Questions