Skip to content

Instantly share code, notes, and snippets.

@r03ert0 r03ert0/extend.js
Created Dec 7, 2017

Embed
What would you like to do?
`extend` function for javascript objects
/**
* @desc From https://gomakethings.com/merging-objects-with-vanilla-javascript/
*/
function extend() {
// Variables
var extended = {};
var deep = false;
var i = 0;
var length = arguments.length;
// Check if a deep merge
if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) {
deep = arguments[0];
i++;
}
// Merge the object into the extended object
var merge = function ( obj ) {
for ( var prop in obj ) {
if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) {
// If deep merge and property is an object, merge properties
if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) {
extended[prop] = extend( true, extended[prop], obj[prop] );
} else {
extended[prop] = obj[prop];
}
}
}
};
// Loop through each object and conduct a merge
for ( i=0; i < length; i++ ) {
var obj = arguments[i];
merge(obj);
}
return extended;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.