Ed Williams
Ed Williams

Reputation: 2497

Ramda: mergeDeepRight + mergeAll (...perhaps mergeDeepRightAll)

Currently in Ramda if I want to deep merge (right) multiple objects I....

var a = _.mergeDeepRight( { one: 1 }, { two: { three: 3 } } )
var b = _.mergeDeepRight( a, { three: { four: 4 } } )
var c = _.mergeDeepRight( b, { four: { five: 5 } } )

// c === { one:1, two: { three: 3 }, three: { four: 4 }, four: { five: 5 } }

If I use _.mergeAll (i.e. _.mergeAll( a, b, c )) it returns { one:1, two: { three:3 } } as _.mergeAll is not deep

Is there a more tidy way of deep merging (right) multiple objects? Something like...

_.mergeDeepRightAll( a, b, c )

Upvotes: 3

Views: 2473

Answers (1)

Ross Mackay
Ross Mackay

Reputation: 972

reduce might be a good call here, as we're transforming a series of items into one.

If we change the input to

var a = mergeDeepRight( { one: 1 }, { two: { three: 3 } } )
var b = { three: { four: 4 } }
var c = { four: { five: 5 } }

We can do

const mergeDeepAll = reduce(mergeDeepRight, {})

mergeDeepAll([a, b, c])

// -> {"four": {"five": 5}, "one": 1, "three": {"four": 4}, "two": {"three": 3}}

And if you wanted to provide the arguments not as an array, you can unapply it, although an array is more in-line with R.mergeAll's signature

const mergeDeepAll = unapply(reduce(mergeDeepRight, {}))

mergeDeepAll(a, b, c)

I'll note that the examples don't actually have any conflicting keys, so a straight up R.mergeAll would work here. Neither of these output in the exact order you mentioned however.

Upvotes: 8

Related Questions