pick

Picks the specified keys from an object.

1.
/**
2.
* Picks the specified keys from an object.
3.
**/
4.
const pick = <T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> => {
5.
const newObj: any = {};
6.
keys.forEach((key) => {
7.
newObj[key] = obj[key];
8.
});
9.
return newObj as Pick<T, K>;
10.
};
11.
12.
export default pick;

1. Installtion

npx @jrtilak/lazykit add pick

2. Parameters

  • obj (T)
    The input object from which properties will be picked.

  • keys (K[])
    An array of keys to pick from the input object. The keys must be valid keys of the input object.

3. Returns

  • Pick<T, K>
    A new object that contains only the specified keys from the input object.

4. Example Usage

1.
import pick from "@/helpers/pick";
2.
3.
const userSettings = {
4.
theme: "light",
5.
language: "fr",
6.
notifications: false,
7.
location: "Canada",
8.
};
9.
10.
const selectedSettings = pick(userSettings, ["theme", "language"]);
11.
12.
console.log(selectedSettings);
13.
// Output: { theme: "light", language: "fr" }