Skip to main content

property()

property<Key>(key): <T>(object) => T[Key]

Creates a function that returns the value at path of a given object.

DEPRECATED

Use an inline arrow function (obj) => obj[key] instead.


Type Parametersโ€‹

Key: Key extends PropertyKeyโ€‹

The type of the key.


Parametersโ€‹

key: Keyโ€‹

The key of the property to get.


Returns: <T>(object): T[Key]โ€‹

A function that returns the property value.


Sinceโ€‹

2.0.0


Also known asโ€‹

prop (Remeda, Ramda) ยท property (Lodash, es-toolkit) ยท โŒ (Radashi, Effect, Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
const users = [{ name: 'fred' }, { name: 'barney' }];
users.map(property('name'));
// => ['fred', 'barney']

// โœ… Recommended approach
const users = [{ name: 'fred' }, { name: 'barney' }];
users.map(user => user.name);
// => ['fred', 'barney']

How it works?โ€‹

Creates a function that returns the value at path of a given object. Deprecated: Use an arrow function.

Native Equivalentโ€‹

// โŒ property('name')
// โœ… obj => obj.name
// โœ… obj => obj?.nested?.value

Use Casesโ€‹

Get property accessor ๐Ÿ“Œโ€‹

Create property accessor function.

const getName = (obj) => obj.name;
users.map(getName);
// => ["Alice", "Bob"]

Dynamic property accessโ€‹

Access property by variable key.

const get = (key) => (obj) => obj[key];
const getAge = get("age");
users.map(getAge);

Pluck valuesโ€‹

Extract property from objects.

items.map(item => item.id);