Aller au contenu principal

pick()

pick<T, K>(object, keys): Pick<T, K>

Creates a new object with only the specified keys.

remarque

Non-existent keys are ignored.


Type Parameters

T: T extends Record<PropertyKey, any>

The type of the input object.

K: K extends string | number | symbol

The type of the keys to pick.


Parameters

object: T

The object to pick keys from.

keys: readonly K[]

Array of keys to pick.


Returns: Pick<T, K>

A new object with only the specified keys.


See Also


Since

2.0.0


Performance

O(k) time & space where k is number of keys to pick. Uses for-of loop and hasOwnProperty check.


Also known as

objectPick (Antfu) · pick (Lodash, es-toolkit, Remeda, Radashi, Ramda, Effect, Modern Dash)


Example

const obj = { a: 1, b: 2, c: 3 };

pick(obj, ['a', 'c']); // => { a: 1, c: 3 }
pick(obj, ['b']); // => { b: 2 }

const user = { id: 1, name: 'John', password: 'secret' };
pick(user, ['id', 'name']); // => { id: 1, name: 'John' }

How it works?

Creates a new object with only the specified keys.

Selection Process

pick vs omit

pickomit
Keepsspecified keysall except specified
Use casewhitelistblacklist

Use Cases

Select specific subsets 📌

Create a shallow copy containing only the specified keys. Critical for creating strict DTOs or filtering API payloads.

const payload = pick(formData, ['username', 'email']);

Extract form subset for validation

Select only the fields relevant to a specific validation step. Useful for multi-step forms or partial schema validation.

const step1Data = pick(formData, ['firstName', 'lastName', 'email']);
const isValid = validateStep1Schema(step1Data);

Whitelist allowed parameters

Ensure that only permitted keys are passed to a function or API. Security critical for preventing mass assignment vulnerabilities.

const safeInput = pick(req.body, ['title', 'content', 'authorId']);
db.create(safeInput);

Extract safe fields for logging

Pick only non-sensitive fields before writing to logs. Critical for compliance (GDPR, HIPAA) and preventing PII leaks in log systems.

const request = {
userId: "u-123",
endpoint: "/api/checkout",
method: "POST",
creditCard: "4111-1111-1111-1111",
ip: "192.168.1.1",
timestamp: 1703001200,
};

const safeLog = pick(request, ["userId", "endpoint", "method", "timestamp"]);
logger.info("API request", safeLog);
// Logs: { userId: "u-123", endpoint: "/api/checkout", method: "POST", timestamp: 1703001200 }
// Credit card and IP never reach the logs