Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Deep Extend / Merge Javascript Objects - underscore.js Mixin

View deep_extend_javascript_objects_underscore_mixin.js
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
/* Copyright (C) 2012-2014 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 )
 
function deepExtend(obj) {
var parentRE = /#{\s*?_\s*?}/,
slice = Array.prototype.slice;
 
_.each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop]) || _.isDate(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 new Error('Trying to combine an array with a non-array (' + prop + ')');
} else {
obj[prop] = _.reject(_.deepExtend(_.clone(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 new Error('Trying to combine an object with a non-object (' + prop + ')');
} else {
obj[prop] = _.deepExtend(_.clone(obj[prop]), source[prop]);
}
} else {
obj[prop] = source[prop];
}
}
});
return obj;
};
 
_.mixin({ 'deepExtend': deepExtend });
 
/**
* 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]
*
**/

License?

Owner

How about GPL?

MIT?..

MIT

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])) {
Owner

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

This is awesome - thank you.

Owner

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

Not getting expected result with Dates.

var a={a: new Date()}
> Object {a: Thu Jun 05 2014 15:29:32 GMT+0200 (CEST)}
var b={a: new Date()}
> Object {a: Thu Jun 05 2014 15:29:38 GMT+0200 (CEST)}
_.deepExtend(a, b)
> Object {a: Thu Jun 05 2014 15:29:32 GMT+0200 (CEST)}

Should be getting 15:29:38 instead of 15:29:32. Missing something?

jsHint says that cyclic complexity is 15, not so good, but thanks anyway=)

Owner

@tkalfigo: Thanks for the heads-up. I've updated the function to make it handle date types correctly. Here's a working Fiddle (all action takes place in the console).

@darkwebdev: I guess you meant 'cyclomatic complexity', since 'cyclic complexity' isn't a thing. See also here and here. Thanks for offering your opinion, though. Feel free to drop back by and leave a note when you've managed to write a significantly less cyclomatically complex version.

Is is buggy:

var a = {name: 'a', items:[]};
_.deepExtend({}, a, {items: [1,2,3]});
// a --- Object {name: "a", items: Array[3]}

Why does it alters a variable?

Owner

@vbarbosh: I'm not able to reproduce that behavior (tested on Chrome '40.0.2214.93 m' and Firefox 35.0.1 running on Windows 8.1 Pro 64bit).

Working Example: http://jsfiddle.net/texinwien/rkkfsqce/2/

Please prepare a working fiddle and let me know what browser you're seeing this behavior on, and I'll try to figure it out.

Owner

@vbarbosh: With a little more playing and testing, I was able to reproduce the behavior you reported. I've worked up a fix that I'm testing right now. I've made a pull request with tested corrections at the github repo, and have also updated the Gist to bring it up to the state of the code at the repo once the pull request is merged (takes care of some other issues reported at the repo, as well).

Thanks for the heads up!

At line 17:

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

will break if have obj[prop] = null and source[prop] = "[Object]"
Is this the correct behaviour?

//For example:
var o = {
     title: null
}
var newO = {
     title: {
       "en-GB" : "My Title"
      }
}
_.deepExtend(o, newO);
> 'Error: Trying to combine an object with a non-object (title)';

I think that o.title should became { "en-GB" : "My Title" }.

If you like, I suggest to change the line in this way:

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

awesome - thank you.

AngeIII commented

Not work as expected:

var x = {
    "defaults": {
        "color": "red",
    },
};

var y = _.deepExtend({},x);

y.defaults.color = "blue";
console.log(x.defaults.color); // "blue"

chrome: 42.0.2311.152 m

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.