Skip to content

Instantly share code, notes, and snippets.

@VitaliyRDev
Forked from cassaram09/deepClone.js
Created November 29, 2018 21:45
Show Gist options
  • Select an option

  • Save VitaliyRDev/6fff7de24479224955503275b696ccde to your computer and use it in GitHub Desktop.

Select an option

Save VitaliyRDev/6fff7de24479224955503275b696ccde to your computer and use it in GitHub Desktop.
JavaScript deep clone function
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