pick()
pick<
T,K>(object,keys):Pick<T,K>
Creates a new object with only the specified keys.
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โ
| pick | omit | |
|---|---|---|
| Keeps | specified keys | all except specified |
| Use case | whitelist | blacklist |
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