Skip to content

Instantly share code, notes, and snippets.

@KMNowak
Created May 6, 2020 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KMNowak/ccef1a55e18fd9d142f4e38a047f8eeb to your computer and use it in GitHub Desktop.
Save KMNowak/ccef1a55e18fd9d142f4e38a047f8eeb to your computer and use it in GitHub Desktop.
Allows to apply given function to all values of given object including elements of an array and sub objects
const isObject = (subj: any) => typeof subj === 'object' && !Array.isArray(subj) && subj !== null;
export const applyToAllProps = (obj: Record<any, any>, fun: (props: any) => any) => {
const appliedEntries: any = Object
.entries(obj)
.map(([key, value]) => ([key, applyToProp(value, fun)]));
return Object.fromEntries(appliedEntries);
};
export const applyToProp = <T = any>(subj: any, fun: (props: any) => any): T | T[] => {
if (isObject(subj)) {
return applyToAllProps(subj, fun);
}
if (Array.isArray(subj)) {
return subj.map(el => applyToProp<any>(el, fun));
}
return fun(subj);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment