Skip to content

Instantly share code, notes, and snippets.

@zettca
Created August 25, 2022 23:19
Show Gist options
  • Save zettca/51e09d83b47f2d518f7784901ac51d90 to your computer and use it in GitHub Desktop.
Save zettca/51e09d83b47f2d518f7784901ac51d90 to your computer and use it in GitHub Desktop.
Delete an object's entry. Doesn't mutate.
export const deleteObjectKey = <T extends Record<string, any>>(
obj: T,
path: string
): T => {
const newObj = { ...obj };
const paths = path.split(".");
paths.reduce((acc, key, idx) => {
if (idx === paths.length - 1) {
delete acc[key];
return true;
}
return acc[key];
}, newObj);
return newObj;
};
@zettca
Copy link
Author

zettca commented Aug 25, 2022

// usage
const newObj = deleteObjectKey(obj, "a.b.c");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment