Last active
September 12, 2021 14:47
-
-
Save uttarwarsandesh33/028dcd7383b101860e7e561af17aac81 to your computer and use it in GitHub Desktop.
Create deep copy with recursive method
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
//recursive method to create deep copy | |
function deepCopy(obj) { | |
if (null === obj || 'object' !== typeof obj) return obj; | |
switch (obj.constructor) { | |
case Boolean: | |
return new Boolean(obj); | |
case Number: | |
return new Number(obj); | |
case String: | |
return new String(obj); | |
case Date: | |
return new Date().setTime(obj.getTime()); | |
case Array: | |
return obj.map((o) => deepCopy1(o)); | |
case RegExp: | |
return new RegExp(obj); | |
case BigInt: | |
return BigInt(obj); | |
case Object: { | |
let copy = {}; | |
Object.keys(obj).forEach((key) => { | |
if (obj.hasOwnProperty(key)) copy[key] = deepCopy1(obj[key]); | |
}); | |
return copy; | |
} | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment