Skip to content

Instantly share code, notes, and snippets.

@pwcberry
Last active February 5, 2025 04:54
Show Gist options
  • Save pwcberry/43582d795f24267cec282295631beb06 to your computer and use it in GitHub Desktop.
Save pwcberry/43582d795f24267cec282295631beb06 to your computer and use it in GitHub Desktop.
TypeScript function to clone a JavaScript object
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