Skip to content

Instantly share code, notes, and snippets.

@ar5had
Forked from azurite/deepCopy.js
Created March 11, 2017 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ar5had/45ce847b2b706f96bd026a812ba3f704 to your computer and use it in GitHub Desktop.
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)
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