Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created October 7, 2016 10:38
Show Gist options
  • Save loretoparisi/610b203d04f2e48cfd6c6b880853e99d to your computer and use it in GitHub Desktop.
Save loretoparisi/610b203d04f2e48cfd6c6b880853e99d to your computer and use it in GitHub Desktop.
Deep Clone a JavaScript Object
function deepClone(obj) {
var copy;
var i;
var len;
if (!obj || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Array) {
copy = [];
for (i = 0, len = obj.length; i < len; i++) {
copy[i] = deepClone(obj[i]);
}
return copy;
}
if (obj instanceof Object) {
copy = Object.create(obj.constructor.prototype);
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
copy[prop] = deepClone(obj[prop]);
}
}
}
return copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment