Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive "merge" or "extend" with Ramda?

I'm trying to find an equivalent function to Lodash's merge using Ramda that does a recursive object key-based "merge" or "extend". The behavior is similar to the following:

let merged = R.someMethod(
  { name: 'Matt', address: { street: 'Hawthorne', number: 22, suffix: 'Ave' }},
  { address: { street: 'Pine', number: 33 }}
);

console.log(merged);

// => { name: 'Matt', address: { street: 'Pine', number: 33, suffix: 'Ave' }}

I noticed in the following pull request that R.set was briefly introduced, but then rolled back soon thereafter. Has this functionality been captured by the Ramda library since?

Is this functionality available in Ramda?

like image 1000
Himmel Avatar asked Jul 01 '16 00:07

Himmel


4 Answers

A relatively simple recursive function can be created using R.mergeWith.

function deepMerge(a, b) {
  return (R.is(Object, a) && R.is(Object, b)) ? R.mergeWith(deepMerge, a, b) : b;
}

deepMerge({ name: 'Matt', address: { street: 'Hawthorne', number: 22, suffix: 'Ave' }},
          { address: { street: 'Pine', number: 33 }});

//=> {"address": {"number": 33, "street": "Pine", "suffix": "Ave"}, "name": "Matt"}
like image 82
Scott Christopher Avatar answered Oct 20 '22 14:10

Scott Christopher


Ramda does not include such a function at the moment.

There have been several attempts to create one, but they seem to founder on the notion of what's really required of such a function.

Feel free to raise an issue if you think it's worth adding.

Update

(Two years later.) This was eventually added, in the form of several functions: mergeDeepLeft, mergeDeepRight, mergeDeepWith, and mergeDeepWithKey.

like image 20
Scott Sauyet Avatar answered Oct 20 '22 15:10

Scott Sauyet


Ramda now has several merge functions: mergeDeepLeft, mergeDeepRight, mergeDeepWith, mergeDeepWithKey.

like image 3
Microcipcip Avatar answered Oct 20 '22 16:10

Microcipcip


const { unapply, mergeDeepRight, reduce } = R
const mergeDeepRightAll = unapply(reduce(mergeDeepRight, {}))

console.log(mergeDeepRightAll({a:1, b: {c: 1}},{a:2, d: {f: 2}},{a:3, b: {c:3}}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
like image 1
cstuncsik Avatar answered Oct 20 '22 16:10

cstuncsik