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

78
Visualizações
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
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