pick
Picks the specified keys from an object.
1. Code
/**
 * Creates a new object with only the specified keys from the original object.
 *
 * @param obj - The original object.
 * @param keys - An array of keys to pick from the original object.
 * @returns A new object with only the specified keys.
 * @typeParam T - The type of the original object.
 * @typeParam K - The type of the keys to pick.
 */
const pick = <T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> => {
  const newObj: any = {};
  keys.forEach((key) => {
    newObj[key] = obj[key];
  });
  return newObj as Pick<T, K>;
};
export default pick;
2. Installation
npx @jrtilak/lazykit@latest add pick -ts3. Description
The pick function picks the specified keys from an object and returns a new object with only those keys.
4. Props
Prop
Type
Default Value
object*object---
keys*array---
5. Examples
import pick from ".";
const obj = { a: 1, b: 2, c: 3 };
const result = pick(obj, ["a", "c"]);
console.log(result);
// Expected output: { a: 1, c: 3 }
const emptyResult = pick(obj, []);
console.log(emptyResult);
// Expected output: {}
const keys = ["a", "b"] as Array<keyof typeof obj>;
// You have to specify the keys as an array of keyof typeof obj to ensure that the keys are valid, If you are defining the keys separately.
const resultWithKeys = pick(obj, keys);
console.log(resultWithKeys);
// Expected output: { a: 1, b: 2 }