Last active
February 5, 2025 04:54
-
-
Save pwcberry/43582d795f24267cec282295631beb06 to your computer and use it in GitHub Desktop.
TypeScript function to clone a JavaScript 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
type Source = { [key: string]: string | number | boolean | object }; | |
export function cloneObject<T>(o: Source): T { | |
const objectCopy = Object.create({}); | |
Object.keys(o).forEach((key) => { | |
if (typeof o[key] !== 'object' || o[key] === null) { | |
objectCopy[key] = o[key]; | |
} else if (Array.isArray(o[key])) { | |
objectCopy[key] = o[key].map(a => typeof a === 'object' ? cloneObject(a) : a); | |
} else { | |
objectCopy[key] = cloneObject(o[key] as Source); | |
} | |
}); | |
return objectCopy as T; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment