Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

70
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda