Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda