Created
February 20, 2012 05:30
-
-
Save afeld/1867987 to your computer and use it in GitHub Desktop.
deepMerge function for underscore.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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