I'm deduping a large array of Objects, many of which have some properties in common. All of the properties are integers.
It's trivially easy to loop through the keys and merge manually, but I can't help but feel like there's some combination of Object.assign and map and reduce that could do this is one line. As the language matures, it seems worth staying ahead of the curve.
EDIT: As an example:
let A = {
"a": 10,
"e": 2,
"g": 14
}
let B = {
"b": 3,
"e": 15,
"f": 1,
"g": 2,
"h": 11
}
let C = Object.magicMerge(A, B)
/*
{
"a": 10,
"e": 17,
"g": 16
"b": 3,
"f": 1,
"h": 11
}
*/
Here's something without loops/reduce:
let C = Object.fromEntries(
Object.keys(A)
.concat(Object.keys(B))
.map(k => [k,
(A[k] || 0) + (B[k] || 0)
])
)
And here's a generic function for any number of objects:
let mergeSum = (...objs) => Object.fromEntries(
Array.from(
new Set(objs.flatMap(Object.keys)),
k => [k,
objs
.map(o => o[k] || 0)
.reduce((a, b) => a + b)
]))
C = mergeSum(A, B)
or even more generic:
let mergeReduce = (objs, fn, init) => Object.fromEntries(
Array.from(
new Set(objs.flatMap(Object.keys)),
k => [k, objs.map(o => o[k]).reduce(fn, init)]
));
// for example:
sumOfProps = mergeReduce([A, B],
(a, b) => (a || 0) + (b || 0))
listOfProps = mergeReduce([A, B],
(a, b) => b ? a.concat(b) : a,
[])