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!
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>