Skip to content

Instantly share code, notes, and snippets.

@Error601
Last active April 4, 2022 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Error601/9a181a0b9f414b752c38 to your computer and use it in GitHub Desktop.
Save Error601/9a181a0b9f414b752c38 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 mergeObjects( /* [true ,] obj1, obj2 [, ...] */ ){
var args = arguments,
arg1 = args[0],
arg2 = args[1] || {},
len = args.length,
deep = false,
i, arg, output = {};
function isObject( obj ){
return Object.prototype.toString.call(obj) === '[object Object]';
}
// 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;
}
@Error601
Copy link
Author

Of course there are plenty of libraries with methods to do exactly what this code snippet does, but... If you need to merge some objects before those load (or are just too "hardcore" to use external libraries), now there's this. So there ya go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment