Skip to content

Instantly share code, notes, and snippets.

@m-sakthi
Created February 28, 2023 15:10
Show Gist options
  • Save m-sakthi/1df51c0c727aabf21c9e9774152ac801 to your computer and use it in GitHub Desktop.
Save m-sakthi/1df51c0c727aabf21c9e9774152ac801 to your computer and use it in GitHub Desktop.
Deep clone of object
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