Created
April 20, 2023 20:46
-
-
Save msichterman/3e315a3e2b90f0a6ef8922d4f8ad555f to your computer and use it in GitHub Desktop.
pickBy Generic Filtering Util
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
export function pickBy<T>(object: T, predicate: (arg: unknown) => boolean) { | |
const obj: T = {} as T; | |
for (const key in object) { | |
if (predicate(object[key])) { | |
obj[key] = object[key]; | |
} | |
} | |
return obj; | |
} | |
// EXAMPLE: | |
// Pick all entries in an object where the value is a string that is not empty | |
// Uses TS generics to properly type the data object | |
const sanitizedData = pickBy<FormSchemaType>( | |
data, | |
(value) => typeof value === "string" && value.length > 0 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment