Created
February 19, 2019 01:31
-
-
Save abhinavnigam2207/03faf78b4247a5c73682008877fa13c2 to your computer and use it in GitHub Desktop.
Create a deep copy of an object.
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
// 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