pluck()
pluck<
T,Key>(collection,path):T[Key][]
Gets the value of property from all elements in collection.
๐ Why is this a Hidden Gem?
Extract a single property from every object in a collection โ cleaner than map + accessor.
DEPRECATED
Use array.map(item => item.property) directly instead.
Type Parametersโ
T: Tโ
The type of elements in the array.
Key: Key extends string | number | symbolโ
The key of the property to pluck.
Parametersโ
collection: Record<string, T> | T[]โ
The collection to iterate over.
path: Keyโ
The path of the property to pluck.
Returns: T[Key][]โ
The new array of property values.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
map (Lodash) ยท pluck (Ramda) ยท โ (es-toolkit, Remeda, Radashi, Effect, Modern Dash, Antfu)
Exampleโ
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 20 }
];
// โ Deprecated approach
const names = pluck(users, 'name');
console.log(names); // ['John', 'Jane', 'Bob']
// โ
Recommended approach
const namesNative = users.map(user => user.name);
console.log(namesNative); // ['John', 'Jane', 'Bob']
How it works?โ
Extracts values of a property from all objects.
Deprecated: Use array.map() directly.
Native Equivalentโ
// โ pluck(arr, 'name')
// โ
arr.map(x => x.name)
Use Casesโ
Extract property from objects ๐โ
Get a specific property from each object in a collection.
const users = [{ name: "Alice" }, { name: "Bob" }, { name: "Charlie" }];
users.map(u => u.name);
// => ["Alice", "Bob", "Charlie"]
Get IDs from collectionโ
Extract identifiers from a list of objects.
const products = [{ id: 1 }, { id: 2 }, { id: 3 }];
products.map(p => p.id);
// => [1, 2, 3]
Collect nested valuesโ
Extract deeply nested properties.
const items = [{ meta: { score: 10 } }, { meta: { score: 20 } }];
items.map(i => i.meta.score);
// => [10, 20]