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

170
Visualizações
Lodash Merge objects and KEEP the duplicates

I need to merge few objects into a single object, but DO NOT remove the duplicates. I've tried to use lodash.merge(), but it is replacing the duplicates. Also same issue with assign, but assign is doing shallow copy only and also replacing the duplicates.

_.merge({}, 
  { a: {
    large: {
      url: '1'
    }
  }}, 
  { b: {
    large: {
      url: '2'
    }
  }}, 
  { c: {
    large: {
      url: '3'
    }
  }}, 
  {a: {
    large: {
      url: '4'
    }
  }});

Result is

{
    "a": {
        "large": {
            "url": "4"
        }
    },
    "b": {
        "large": {
            "url": "2"
        }
    },
    "c": {
        "large": {
            "url": "3"
        }
    }
}

But i need

{
     "a": {
         "large": {
             "url": "1"
          }
      },
      "b": {
          "large": {
             "url": "2"
          }
      },
      "c": {
          "large": {
              "url": "3"
          }
       },
      "a": {
          "large": {
               "url": "4"
          }
      },
    }

Please, help!

How can i keep the duplicates? Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could use mergeWith() to customize how the merge happens. In your case I'd suggest creating an array for any duplicate objects.

To do this, we'd create a mergeCustomizer() function that will output an array if we get duplicates.

function mergeCustomizer(objValue, srcValue) {
  if (objValue) {
    return  [objValue].flat().concat(srcValue);
  }
  return srcValue 
}

let merged = _.mergeWith({}, 
  { a: {
    large: {
      url: '1'
    }
  }}, 
  { b: {
    large: {
      url: '2'
    }
  }}, 
  { c: {
    large: {
      url: '3'
    }
  }}, 
  {a: {
    large: {
      url: '4'
    }
  }}, mergeCustomizer);
  
console.log('Merged:',merged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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