Last active
October 12, 2021 06:22
-
-
Save cassaram09/e6eb7b289f97128e4e45f0d720475c12 to your computer and use it in GitHub Desktop.
JavaScript deep clone function
This file contains hidden or 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(source){ | |
// If the source isn't an Object or Array, throw an error. | |
if ( !(source instanceof Object) || source instanceof Date || source instanceof String) { | |
throw 'Only Objects or Arrays are supported.' | |
} | |
// Set the target data type before copying. | |
var target = source instanceof Array ? [] : {}; | |
for (let prop in source){ | |
// Make sure the property isn't on the protoype | |
if ( source instanceof Object && !(source instanceof Array) && !(source.hasOwnProperty(prop)) ) { | |
continue; | |
} | |
// If the current property is an Array or Object, recursively clone it, else copy it's value | |
if ( source[prop] instanceof Object && !(source[prop] instanceof Date) && !(source[prop] instanceof String) ) { | |
target[prop] = deepClone(source[prop]) | |
} else { | |
target[prop] = source[prop] | |
} | |
} | |
return target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment