Skip to content

Instantly share code, notes, and snippets.

@Istar-Eldritch
Created June 10, 2016 21:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Istar-Eldritch/e2211246a9531376d0a01ea44b054b41 to your computer and use it in GitHub Desktop.
Save Istar-Eldritch/e2211246a9531376d0a01ea44b054b41 to your computer and use it in GitHub Desktop.
Ramda deep merge.
var R = require('ramda')
var one = {
test: {
a: 1,
b: 2
},
pemento: "sipi",
arr: ['a', 'b']
}
var two = {
test: {
a:3,
c:4
},
pemento: "nope",
arr: ['b', 'c']
}
function deepMerge(v1, v2) {
if(Array.isArray(v1) && Array.isArray(v2)) {
return R.uniq(R.concat(v1, v2));
}
else if(typeof v1 === 'object' && typeof v2 === 'object'){
return R.mergeWith(deepMerge, v1, v2)
}
else {
return v2;
}
}
R.mergeWith(deepMerge,one, two)
@thomasschiet
Copy link

The second if statement should also check if v1 and v2 are null, because typeof null === 'object'.

function deepMerge(v1, v2) {
  if(Array.isArray(v1) && Array.isArray(v2)) {
    return R.uniq(R.concat(v1, v2));
  }
  else if(typeof v1 === 'object' && typeof v2 === 'object' && !R.isNil(v1) && !R.isNil(v2)){
    return R.mergeWith(deepMerge, v1, v2)
  }
  else {
    return v2;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment