Last active
June 20, 2017 18:11
-
-
Save stevepaulo/11186234 to your computer and use it in GitHub Desktop.
deep copy JS object
This file contains 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
let o1 = { p1: 'v1', p2: { p3: 'v3' }, p4: ['a', 'b', 'c'], p5: 1, p6: false, p7: null, p8: undefined }; | |
function deepCopy(o) { | |
let o_copy = {} | |
for (var p in o) { | |
if (o.hasOwnProperty(p)) { | |
if (typeof o[p] === 'object' && !(Array.isArray(o[p]) || o[p] == null)) { | |
o_copy[p] = deepCopy(o[p]); | |
} else { | |
o_copy[p] = o[p] | |
} | |
} | |
} | |
return o_copy; | |
} | |
let o2 = deepCopy(o1); | |
// note the following works for all values other than 'undefined': | |
let o2 = JSON.parse(JSON.stringify(o1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment