1.38.0pick
Creates a new object containing only the specified properties that exist on the object or its prototype chain.
pick(object, keys):Pick<T, K>How it works
The function creates a new object and checks each requested key with the in operator. If the key exists anywhere on the object or its prototype chain, its current value is copied to the result.
Prototype chain
Unlike a check based on hasOwnProperty, the in operator also considers inherited properties. Therefore, an inherited property can be included in the resulting object.
Shallow copy
The selected values are copied by reference. Nested objects and arrays are not cloned.
Original object
The function creates a separate result object and does not directly modify the input object.
Parameters
objectTrequiredThe object from which properties should be selected.
keysK[]requiredAn array of keys to include in the resulting object.
Returns
Pick<T, K>A new object containing the requested properties that exist on the object or its prototype chain.
Examples
Basic usage
const user = {
name: "Amir",
age: 22,
role: "developer",
};
pick(user, ["name", "age"]);
// {
// name: "Amir",
// age: 22,
// }Pick a single property
const user = {
name: "Amir",
age: 22,
};
pick(user, ["name"]);
// {
// name: "Amir",
// }Pick multiple properties
const user = {
name: "Amir",
age: 22,
email: "amir@example.com",
};
pick(user, ["name", "email"]);
// {
// name: "Amir",
// email: "amir@example.com",
// }Empty keys
const user = {
name: "Amir",
age: 22,
};
pick(user, []);
// {}Undefined values are included
const data = {
value: undefined,
};
pick(data, ["value"]);
// {
// value: undefined,
// }Inherited properties
const parent = {
role: "admin",
};
const user = Object.create(parent);
user.name = "Amir";
pick(user, ["role"]);
// {
// role: "admin",
// }Own and inherited properties
const parent = {
role: "admin",
};
const user = Object.create(parent);
user.name = "Amir";
pick(user, ["name", "role"]);
// {
// name: "Amir",
// role: "admin",
// }Missing properties
const user = {
name: "Amir",
};
pick(user, ["name"]);
// {
// name: "Amir",
// }
// TypeScript restricts K to keyof T,
// so arbitrary missing keys cannot normally be passed.Original object is unchanged
const user = {
name: "Amir",
age: 22,
};
const result = pick(user, ["name"]);
console.log(user);
// {
// name: "Amir",
// age: 22,
// }Nested values keep their references
const user = {
name: "Amir",
profile: {
age: 22,
},
};
const result = pick(user, ["profile"]);
result.profile.age = 25;
console.log(user.profile.age);
// 25