Last active
August 29, 2015 14:05
-
-
Save MadeByMike/e57dd16797acf5d105b5 to your computer and use it in GitHub Desktop.
jQuery.mergeObjects()
This file contains hidden or 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
(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