Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!