I have two objects created with Lodash’s groupBy like this:
const prevGroupedData = {
'01/04/2000': [{data: 1}, {data: 2}, {data: 3}],
'02/04/2000': [{data: 1}, {data: 2}]
}
const GroupedData = {
'02/04/2000': [{data: 3}, {data: 4}],
'03/04/2000': [{data: 1}]
}
So when I merge these two objects, I wanna make sure that it is the prevGroupedData that is merged first, that means something like:
const result = {
'01/04/2000': [{data: 1}, {data: 2}, {data: 3}],
'02/04/2000': [{data: 1}, {data: 2}, {data: 3}, {data: 4}],
'03/04/2000': [{data: 1}]
}
But not:
const result = {
'01/04/2000': [{data: 1}, {data: 2}, {data: 3}],
'02/04/2000': [{data: 3}, {data: 4}, {data: 1}, {data: 2}],
'03/04/2000': [{data: 1}]
}
I have tried something like lodash’s merge but it gives the second result:
let result = _.merge(prevGroupedData, GroupedData);
//gives second result
So how do I make sure that it is the prevGroupedData that has higher priority when there’s duplicated keys?
2
Answers
this is possible with
mergeWith
. The docs have a similar looking exampleNote that the above has mutated the
prevGroupedData
. If you don’t need that to happen you can assign an empty{}
as the destination.As
_.merge
does not handle combining arrays, you can use_.mergeWith
and pass a customizer to concatenate arrays.