Skip to content

Instantly share code, notes, and snippets.

@serhatates
Last active December 13, 2018 11:11
Show Gist options
  • Save serhatates/d61566b6cdb29134bca4a9c1f813afbd to your computer and use it in GitHub Desktop.
Save serhatates/d61566b6cdb29134bca4a9c1f813afbd to your computer and use it in GitHub Desktop.
Deep Copy(Clone) arrays, objects, null, strings, numbers, (no Date)
// var testObj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
function deepCopy(o) {
// if not array or object or is null return self
if (typeof o !== 'object'||o === null) return o;
let newO, i;
// handle case: array
if (o instanceof Array) {
let l;
newO = [];
for (i = 0, l = o.length; i < l; i++) newO[i] = deepCopy(o[i]);
return newO;
}
// handle case: object
newO = {};
for (i in o) if (o[i] !== undefined) newO[i] = deepCopy(o[i]);
return newO;
}
// var obj2 = deepCopy(testObj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment