Skip to content

Instantly share code, notes, and snippets.

@afeld
Created February 20, 2012 05:30
Show Gist options
  • Save afeld/1867987 to your computer and use it in GitHub Desktop.
Save afeld/1867987 to your computer and use it in GitHub Desktop.
deepMerge function for underscore.js
deepMerge: function(dest){
_.each(_.rest(arguments), function(source){
var sourceVal, destVal;
for (var prop in source){
sourceVal = source[prop];
destVal = dest[prop];
if (prop in dest && _.isObject(sourceVal) && _.isObject(destVal)){
_.deepMerge(destVal, sourceVal);
} else {
dest[prop] = sourceVal;
}
}
});
return dest;
}
module("_.deepMerge");
test("flat objects", function(){
var obj = {foo: 'bar'};
_.deepMerge(obj, {baz: 'blip'});
deepEqual(obj, {
foo: 'bar',
baz: 'blip'
});
});
test("nested objects", function(){
var obj = {
foo: {
bar: 'baz'
}
};
_.deepMerge(obj, {
foo: {
hi: 'there'
}
});
deepEqual(obj, {
foo: {
bar: 'baz',
hi: 'there'
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment