Created
February 28, 2023 15:10
-
-
Save m-sakthi/1df51c0c727aabf21c9e9774152ac801 to your computer and use it in GitHub Desktop.
Deep clone of 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
const deepClone = (obj) => { | |
if (obj === null || typeof obj !== "object") return obj; | |
let clone = Array.isArray(obj) ? [] : {}; | |
for (const key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
clone[key] = | |
obj[key] instanceof Date | |
? new Date(obj[key].getTime()) | |
: deepClone(obj[key]); | |
} | |
} | |
return clone; | |
}; | |
// example | |
// const original = { a: 1, b: { c: new Date() } }; | |
// const clone = deepClone(original); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment