CyrefJS
CCyrefJS
فا
Back to documentation
Object/Since 1.38.0

pick

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

objectTrequired

The object from which properties should be selected.

keysK[]required

An 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

01

Basic usage

TypeScript
const user = {
  name: "Amir",
  age: 22,
  role: "developer",
};

pick(user, ["name", "age"]);
// {
//   name: "Amir",
//   age: 22,
// }
02

Pick a single property

TypeScript
const user = {
  name: "Amir",
  age: 22,
};

pick(user, ["name"]);
// {
//   name: "Amir",
// }
03

Pick multiple properties

TypeScript
const user = {
  name: "Amir",
  age: 22,
  email: "amir@example.com",
};

pick(user, ["name", "email"]);
// {
//   name: "Amir",
//   email: "amir@example.com",
// }
04

Empty keys

TypeScript
const user = {
  name: "Amir",
  age: 22,
};

pick(user, []);
// {}
05

Undefined values are included

TypeScript
const data = {
  value: undefined,
};

pick(data, ["value"]);
// {
//   value: undefined,
// }
06

Inherited properties

TypeScript
const parent = {
  role: "admin",
};

const user = Object.create(parent);
user.name = "Amir";

pick(user, ["role"]);
// {
//   role: "admin",
// }
07

Own and inherited properties

TypeScript
const parent = {
  role: "admin",
};

const user = Object.create(parent);
user.name = "Amir";

pick(user, ["name", "role"]);
// {
//   name: "Amir",
//   role: "admin",
// }
08

Missing properties

TypeScript
const user = {
  name: "Amir",
};

pick(user, ["name"]);
// {
//   name: "Amir",
// }

// TypeScript restricts K to keyof T,
// so arbitrary missing keys cannot normally be passed.
09

Original object is unchanged

TypeScript
const user = {
  name: "Amir",
  age: 22,
};

const result = pick(user, ["name"]);

console.log(user);
// {
//   name: "Amir",
//   age: 22,
// }
10

Nested values keep their references

TypeScript
const user = {
  name: "Amir",
  profile: {
    age: 22,
  },
};

const result = pick(user, ["profile"]);

result.profile.age = 25;

console.log(user.profile.age);
// 25
Built with@cyref/js·Official documentation