Skip to content

Instantly share code, notes, and snippets.

@stevepaulo
Last active June 20, 2017 18:11
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 stevepaulo/11186234 to your computer and use it in GitHub Desktop.
Save stevepaulo/11186234 to your computer and use it in GitHub Desktop.
deep copy JS object
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