pick

Picks the specified keys from an object.

1. Code

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

3. 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 }