Skip to content

Instantly share code, notes, and snippets.

@mflorida
Forked from Error601/mergeObjects.js
Last active April 30, 2023 08:20
Show Gist options
  • Save mflorida/557e6d737d1a5021b0fd91d24e98081f to your computer and use it in GitHub Desktop.
Save mflorida/557e6d737d1a5021b0fd91d24e98081f to your computer and use it in GitHub Desktop.
Merge/Extend Objects in native JS
/*!
* 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