Last active
December 13, 2018 11:11
-
-
Save serhatates/d61566b6cdb29134bca4a9c1f813afbd to your computer and use it in GitHub Desktop.
Deep Copy(Clone) arrays, objects, null, strings, numbers, (no Date)
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
// 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