Skip to content

Instantly share code, notes, and snippets.

@gate3
Created July 5, 2018 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gate3/8fae1b3ebf8e62d84ec1c024ecd59e61 to your computer and use it in GitHub Desktop.
Save gate3/8fae1b3ebf8e62d84ec1c024ecd59e61 to your computer and use it in GitHub Desktop.
Deepclone javascript function
function deepClone(object) {
//first check if it is any of the types seen as object in javascript
if(typeof object !== 'object'){
throw new Error('please provide an object')
}
/*
We need to compare using Object.prototype because typeof only comparse by type and type for dates and arrays are always object. While Object.prototype compares the constructor
*/
var clone = Object.prototype.toString.call(object) !== '[object Object]' ? object:{}
for(var i in object) {
/*
when the current iteration of the object isn't null and is of type object recursively clone. Because of the comparison we already made with clone above it will return the correct object type and not {}
*/
if(object[i] != null && typeof(object[i])=="object")
clone[i] = deepClone(object[i]);
else
clone[i] = object[i];
}
return clone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment