array unique merge
nikitapilgrim opened this issue · comments
object-merge-advanced
I need to merge objects, but they can contain arrays with the same objects inside. I need to merge an array into 1, but only unique objects. Can I do this with your library?
const data1 = {
[year]: {
[month]: {
[day]: [message],
},
},
};
const _data2 = {
[year]: {
[month]: {
[day]: [message],
},
},
};
hi!
When arrays of plain objects are merged, only unique-ones are kept — this comes out of the box — see https://stackblitz.com/edit/js-shkm7d?file=index.js
Now, if this doesn't suit, you can override the merging algorithm via opts.cb
.
mergeAdvanced(
{
...
},
{
...
},
{
cb: (inputArg1, inputArg2, resultAboutToBeReturned, infoObj) => {
// whatever you return here gets written as the value of clashing keys:
return resultAboutToBeReturned
},
},
)
You can also use the infoObj
, evaluate paths by regex'ing them and conditionally merging only "special" cases, arrays of objects.
General plan would be:
- in the callback function, isolate the paths that need special merging, use IF-ELSE, on ELSE return
resultAboutToBeReturned
. - if we need to produce an array of unique plain objects, that's
array.reduce
, and evaluation would be, I supposelodash.isequal
orfast-deep-equal
libraries (something that can compare objects by values, as opposed to comparing objects themselves via===
)
If you get stuck, post here more realistic sample inputs + the desired result — I'll help to write a callback function.
Good luck!