Created
May 6, 2020 17:13
-
-
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
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
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