Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

pick

Returns a new object composed of the specified keys from the input object.

TypeScript
Copied!
1/**
2 * Returns a new object composed of the specified keys from the input object.
3 *
4 * @param obj - The source object.
5 * @param keys - An array of keys to pick from the object.
6 * @returns A new object with only the specified keys.
7 */
8export function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
9  return keys.reduce((res, key) => {
10    if (key in obj) {
11      res[key] = obj[key];
12    }
13    return res;
14  }, {} as Pick<T, K>);
15}
  • Selective Property Extraction

    Allows precise control over which properties to include, improving performance and security by excluding unnecessary data.

  • Type-Safe with Inferred Keys

    Uses keyof and Pick in TypeScript to ensure compile-time correctness and accurate return types.

  • Immutable Result

    Returns a new object rather than modifying the original, supporting functional and predictable patterns.

  • Clean and Minimal Implementation

    Leverages reduce for concise logic that is easy to read and maintain.

Tests | Examples

TypeScript
Copied!
1test('pick - picks specified keys from flat object', () => {
2  const obj = { a: 1, b: 2, c: 3 };
3  expect(pick(obj, ['a', 'c'])).toEqual({ a: 1, c: 3 });
4});
5
6test('pick - returns empty object when keys not found', () => {
7  const obj = { a: 1, b: 2 };
8  expect(pick(obj, ['x' as any, 'y' as any])).toEqual({});
9});
10
11test('pick - returns empty object when empty keys array', () => {
12  const obj = { a: 1, b: 2 };
13  expect(pick(obj, [])).toEqual({});
14});
15
16test('pick - handles missing keys gracefully', () => {
17  const obj = { a: 1, b: 2 };
18  expect(pick(obj, ['a', 'c' as any])).toEqual({ a: 1 });
19});
20
21test('pick - preserves value types', () => {
22  const obj = { a: 1, b: 'two', c: true };
23  const picked = pick(obj, ['b', 'c']);
24  expect(picked).toEqual({ b: 'two', c: true });
25});

Common Use Cases

  • API Response Shaping

    Return only specific fields from an object when exposing data through APIs or serializers.

  • Form Field Isolation

    Extract selected fields from form state or user input for validation or submission.

  • State Management

    Selectively derive substate or pass specific props to components from global or local state.

  • Logging and Debugging

    Print or track only relevant fields without dumping full object contents.

  • Permission-Based Data Filtering

    Serve only allowed fields to users based on roles or access rules.

Codebase: Utilities -> Objects -> pick | Yevhen Klymentiev