Created
July 6, 2026 16:58
-
-
Save devhammed/ac317641ba1a67913be39659ae4ae4a0 to your computer and use it in GitHub Desktop.
Helper hook to extract key or key-value pairs from an array of objects.
This file contains hidden or 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
| import { useMemo } from 'react'; | |
| export type UsePluckKeys<T, K extends keyof T> = T[K][]; | |
| export type UsePluckKeyValues<T, K extends keyof T, V extends keyof T> = Record<T[K] & PropertyKey, T[V]>; | |
| export type UsePluck<T, K extends keyof T, V extends keyof T> = UsePluckKeys<T, K> | UsePluckKeyValues<T, K, V>; | |
| export function usePluck<T, K extends keyof T>(options: T[], key: K): UsePluckKeys<T, K>; | |
| export function usePluck<T, K extends keyof T, V extends keyof T>( | |
| options: T[], | |
| key: K, | |
| value: V, | |
| ): UsePluckKeyValues<T, K, V>; | |
| export function usePluck<T, K extends keyof T, V extends keyof T>(options: T[], key: K, value?: V) { | |
| return useMemo<UsePluck<T, K, V>>(() => { | |
| if (value === undefined) { | |
| return options.map(option => option[key]) as UsePluckKeys<T, K>; | |
| } | |
| return Object.fromEntries(options.map(option => [option[key], option[value]])) as UsePluckKeyValues<T, K, V>; | |
| }, [options, key, value]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment