Skip to content

Instantly share code, notes, and snippets.

@MadeByMike
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MadeByMike/e57dd16797acf5d105b5 to your computer and use it in GitHub Desktop.
Save MadeByMike/e57dd16797acf5d105b5 to your computer and use it in GitHub Desktop.
jQuery.mergeObjects()
(function($) {
$.mergeObjects = function(objects, merge_cb) {
var options, name, src, copy, copyIsArray, clone,
target = objects[0] || {},
i = 1,
length = objects.length;
// Handle case when target is a string or something
if ( typeof target !== "object" && !$.isFunction(target) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = objects[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( copy && ( $.isPlainObject(copy) ||
(copyIsArray = $.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && $.isArray(src) ? src : [];
} else {
clone = src && $.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = $.mergeObjects( [clone, copy], merge_cb);
// Don't bring in undefined values
} else if ( copy !== undefined ) {
if ($.isFunction(merge_cb)){
if(merge_cb(target[ name ], copy) !== undefined ){
target[ name ] = merge_cb(target[ name ], copy)
}
} else {
target[ name ] = copy;
}
}
}
}
}
// Return the modified object
return target;
}
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment