-
-
Save mflorida/557e6d737d1a5021b0fd91d24e98081f to your computer and use it in GitHub Desktop.
Merge/Extend Objects in native JS
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
/*! | |
* Replace some functionality of jQuery's $.extend() method | |
* with only native JavaScript. Unlike $.extend(), this | |
* function will ONLY merge plain objects (not arrays). | |
* https://gist.github.com/Error601/9a181a0b9f414b752c38 | |
*/ | |
function isObject( obj ){ | |
return Object.prototype.toString.call(obj) === '[object Object]'; | |
} | |
function mergeObjects( /* [true ,] obj1, obj2 [, ...] */ ){ | |
var args = arguments, | |
arg1 = args[0], | |
arg2 = args[1] || {}, | |
len = args.length, | |
deep = false, | |
i, arg, output = {}; | |
// first argument will be output object | |
if ( isObject(arg1) ){ | |
output = arg1; | |
} | |
// unless set to true | |
else if ( arg1.toString() === "true" ){ | |
deep = true; | |
output = arg2; | |
} | |
// stop here and return the output object | |
// if argument length is 0 or 1, or | |
// if we're trying to deep merge a single object | |
if ( len <= 1 || (deep && len === 2) ){ | |
return output; | |
} | |
function processObject( obj ){ | |
var prop; | |
for ( prop in obj ){ | |
if ( obj.hasOwnProperty(prop) ){ | |
if ( deep && isObject(obj[prop]) ){ | |
output[prop] = mergeObjects( deep, output[prop], obj[prop] ); | |
} | |
else { | |
output[prop] = obj[prop]; | |
} | |
} | |
} | |
} | |
// loop over additional arguments | |
for ( i = 1; i < len; i++ ){ | |
arg = args[i]; | |
if ( isObject(arg) ) { | |
processObject(arg); | |
} | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment