Created
October 7, 2016 10:38
-
-
Save loretoparisi/610b203d04f2e48cfd6c6b880853e99d to your computer and use it in GitHub Desktop.
Deep Clone a JavaScript Object
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(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