Skip to content

Picker

Gets the new object with the specified keys from the original object.

๐ŸŽฌ Usage

<script>
    import {picker} from "@sveu/shared/dicts"

    const obj = {"Mila": "Kunis", "Emma": "Watson", "Scarlett": "Johansson"}

    picker(obj, ["Mila", "Emma"]) // {"Mila": "Kunis", "Emma": "Watson"}
</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
obj object to pick from Record<string | number | symbol, any> yes
keys keys to pick string[] yes
omit_undefined omit keys with undefined values boolean no

โ†ฉ๏ธ Returns

A new object with the specified keys.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
/**
 * Gets the new object with the specified keys from the original object.
 *
 * @param obj - The original object.
 *
 * @param keys - The keys to pick.
 *
 * @param omit_undefined - If true, the keys with undefined values will be omitted.
 *
 * @returns The new object with the specified keys from the original object
 */
export function picker<
    O extends Record<string | number | symbol, any>,
    T extends keyof O
>(obj: O, keys: T[], omit_undefined = false) {
    return keys.reduce((n, k) => {
        if (k in obj) {
            if (!omit_undefined || obj[k] !== undefined) n[k] = obj[k]
        }
        return n
    }, {} as Pick<O, T>)
}

Last update: 2023-02-14