Deep Extend / Merge Javascript Objects - underscore.js Mixin

  • Download Gist
deep_extend_javascript_objects_underscore_mixin.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
/* Copyright (C) 2012-2013 Kurt Milam - http://xioup.com | Source: https://gist.github.com/1868955
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
 
// Based conceptually on the _.extend() function in underscore.js ( see http://documentcloud.github.com/underscore/#extend for more details )
 
deepExtend = function(obj) {
var parentRE = /#{\s*?_\s*?}/,
slice = Array.prototype.slice,
hasOwnProperty = Object.prototype.hasOwnProperty;
 
_.each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (hasOwnProperty.call(source, prop)) {
if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop])) {
obj[prop] = source[prop];
}
else if (_.isString(source[prop]) && parentRE.test(source[prop])) {
if (_.isString(obj[prop])) {
obj[prop] = source[prop].replace(parentRE, obj[prop]);
}
}
else if (_.isArray(obj[prop]) || _.isArray(source[prop])){
if (!_.isArray(obj[prop]) || !_.isArray(source[prop])){
throw 'Error: Trying to combine an array with a non-array (' + prop + ')';
} else {
obj[prop] = _.reject(_.deepExtend(obj[prop], source[prop]), function (item) { return _.isNull(item);});
}
}
else if (_.isObject(obj[prop]) || _.isObject(source[prop])){
if (!_.isObject(obj[prop]) || !_.isObject(source[prop])){
throw 'Error: Trying to combine an object with a non-object (' + prop + ')';
} else {
obj[prop] = _.deepExtend(obj[prop], source[prop]);
}
} else {
obj[prop] = source[prop];
}
}
}
});
return obj;
};
 
/**
* Dependency: underscore.js ( http://documentcloud.github.com/underscore/ )
*
* Mix it in with underscore.js:
* _.mixin({deepExtend: deepExtend});
*
* Call it like this:
* var myObj = _.deepExtend(grandparent, child, grandchild, greatgrandchild)
*
* Notes:
* Keep it DRY.
* This function is especially useful if you're working with JSON config documents. It allows you to create a default
* config document with the most common settings, then override those settings for specific cases. It accepts any
* number of objects as arguments, giving you fine-grained control over your config document hierarchy.
*
* Special Features and Considerations:
* - parentRE allows you to concatenate strings. example:
* var obj = _.deepExtend({url: "www.example.com"}, {url: "http://#{_}/path/to/file.html"});
* console.log(obj.url);
* output: "http://www.example.com/path/to/file.html"
*
* - parentRE also acts as a placeholder, which can be useful when you need to change one value in an array, while
* leaving the others untouched. example:
* var arr = _.deepExtend([100, {id: 1234}, true, "foo", [250, 500]],
* ["#{_}", "#{_}", false, "#{_}", "#{_}"]);
* console.log(arr);
* output: [100, {id: 1234}, false, "foo", [250, 500]]
*
* - The previous example can also be written like this:
* var arr = _.deepExtend([100, {id:1234}, true, "foo", [250, 500]],
* ["#{_}", {}, false, "#{_}", []]);
* console.log(arr);
* output: [100, {id: 1234}, false, "foo", [250, 500]]
*
* - And also like this:
* var arr = _.deepExtend([100, {id:1234}, true, "foo", [250, 500]],
* ["#{_}", {}, false]);
* console.log(arr);
* output: [100, {id: 1234}, false, "foo", [250, 500]]
*
* - Array order is important. example:
* var arr = _.deepExtend([1, 2, 3, 4], [1, 4, 3, 2]);
* console.log(arr);
* output: [1, 4, 3, 2]
*
* - You can remove an array element set in a parent object by setting the same index value to null in a child object.
* example:
* var obj = _.deepExtend({arr: [1, 2, 3, 4]}, {arr: ["#{_}", null]});
* console.log(obj.arr);
* output: [1, 3, 4]
*
**/

Now available as a node/AMD package:

https://github.com/pygy/underscoreDeepExtend

Edit: corrected the URL

It also works as-is in the browser.

I forked it and added support for copying properties that are functions to line 20.

{
  foo: function(){}
}

will now get copied instead of attempting to deepExtend it (functions are "objects" in javascript, so the branching sent it to deepExtend again, on line 39).

It fails to delete an element in a parent by setting it to null in a child, if the type of this element is either Object or Array.

I fixed it with this (I used fork by @wulftone):

if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop])) {

@wulftone & @kapooostin : Thanks for the updates! I went ahead and incorporated both into this gist.

This is awesome - thank you.

I've change the license from GPL to expat (MIT) due to popular demand.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.