-
-
Save ar5had/45ce847b2b706f96bd026a812ba3f704 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) { | |
var copy; | |
if(Array.isArray(o)) { | |
copy = []; | |
for(var i = 0; i < o.length; i++) { | |
if(isPrimitive(o[i])) { | |
copy[i] = o[i]; | |
} | |
else { | |
copy[i] = deepCopy(o[i]); | |
} | |
} | |
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 { | |
copy[p] = deepCopy(o[p]); | |
} | |
} | |
} | |
return copy; | |
} | |
else { | |
return o; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment