Skip to content

Instantly share code, notes, and snippets.

@abhinavnigam2207
Created February 19, 2019 01:31
Show Gist options
  • Save abhinavnigam2207/03faf78b4247a5c73682008877fa13c2 to your computer and use it in GitHub Desktop.
Save abhinavnigam2207/03faf78b4247a5c73682008877fa13c2 to your computer and use it in GitHub Desktop.
Create a deep copy of an object.
// Method 1
let obj = {
a: 1,
b: {
c: 2,
},
}
let newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } }
// Method 2
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i])=="object")
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
let newObj = cloneObject(obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment