Last active
March 11, 2017 18:57
-
-
Save azurite/dba1151cb2ff79606fa54c542417192f to your computer and use it in GitHub Desktop.
Quick and dirty way to deep copy json objects in javascript (object prototypes are not copied)
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 isNull(v) { | |
return typeof v === "object" && !v; | |
} | |
function isPrimitive(v) { | |
return ["number", "string", "boolean", "undefined"].indexOf(typeof v) !== -1 || isNull(v); | |
} | |
function isPlainObject(o) { | |
return o && typeof o === "object" && o.constructor === Object; | |
} | |
function deepCopy(o, level = Infinity) { | |
var copy; | |
if(Array.isArray(o)) { | |
copy = []; | |
for(var i = 0; i < o.length; i++) { | |
if(isPrimitive(o[i])) { | |
copy[i] = o[i]; | |
} | |
else { | |
if(level != 0) { | |
copy[i] = deepCopy(o[i], level - 1); | |
} | |
else { | |
copy[i] = undefined; | |
} | |
} | |
} | |
return copy; | |
} | |
else if(isPlainObject(o)) { | |
copy = {}; | |
for(var p in o) { | |
if(o.hasOwnProperty(p)) { | |
if(isPrimitive(o[p])) { | |
copy[p] = o[p]; | |
} | |
else { | |
if(level != 0) { | |
copy[p] = deepCopy(o[p], level - 1); | |
} | |
else { | |
copy[p] = undefined; | |
} | |
} | |
} | |
} | |
return copy; | |
} | |
else { | |
return o; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment