Skip to content

Instantly share code, notes, and snippets.

@msichterman
Created April 20, 2023 20:46
Show Gist options
  • Save msichterman/3e315a3e2b90f0a6ef8922d4f8ad555f to your computer and use it in GitHub Desktop.
Save msichterman/3e315a3e2b90f0a6ef8922d4f8ad555f to your computer and use it in GitHub Desktop.
pickBy Generic Filtering Util
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