Created
July 5, 2018 11:02
-
-
Save gate3/8fae1b3ebf8e62d84ec1c024ecd59e61 to your computer and use it in GitHub Desktop.
Deepclone javascript function
This file contains 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
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