Table of Contents#
- What is _.pluck?
- Syntax and Parameters
- Return Value
- Basic Example
- Advanced Examples
- Common Use Cases
- Common Practices
- Best Practices
- Limitations and Edge Cases
- Alternatives to _.pluck
- Conclusion
- References
What is _.pluck?#
_.pluck is a utility function in Underscore.js designed to extract the value of a specific property from each element in a collection (array or object). It iterates over the collection, accesses the specified property for each element, and returns a new array containing these values in the same order as the original collection.
In essence, _.pluck is a specialized version of _.map (Underscore’s iteration function) optimized for the common task of extracting property values. It simplifies code that would otherwise require writing a custom _.map callback to access the property.
Syntax and Parameters#
The syntax for _.pluck is straightforward:
_.pluck(list, propertyName)Parameters:#
list(Array|Object): The collection to iterate over. This can be an array (where elements are objects) or an object (where values are objects; keys are ignored, and iteration is over values).propertyName(String|Number): The name of the property to extract from each element. For arrays of arrays, this can be a numeric index (e.g.,0to extract the first element of each sub-array).
Return Value#
_.pluck returns a new array containing the values of the specified propertyName from each element in list. If an element does not have the specified property, undefined is included in the result for that element.
Basic Example#
Let’s start with a simple example. Suppose we have an array of user objects, each with name and age properties. We want to extract all name values into a new array:
// Import Underscore.js (assuming it's loaded via CDN or module)
const _ = require('underscore'); // or include via <script> in browsers
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
];
// Extract the 'name' property from each user
const userNames = _.pluck(users, 'name');
console.log(userNames); // Output: ['Alice', 'Bob', 'Charlie']Here, _.pluck iterates over the users array, accesses the name property of each object, and returns ['Alice', 'Bob', 'Charlie'].
Advanced Examples#
Example 1: Extracting from an Object (Instead of Array)#
_.pluck works with objects too. It iterates over the values of the object (ignoring keys) and extracts the property:
const userData = {
alice: { id: 1, email: '[email protected]' },
bob: { id: 2, email: '[email protected]' },
charlie: { id: 3, email: '[email protected]' }
};
// Extract 'email' from each value in userData
const emails = _.pluck(userData, 'email');
console.log(emails); // Output: ['[email protected]', '[email protected]', '[email protected]']Note: The order of values in the result depends on the object’s key insertion order (consistent in ES6+ environments).
Example 2: Extracting from Arrays of Arrays#
If the collection is an array of arrays, use a numeric propertyName to extract elements by index:
const matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
];
// Extract the first element (index 0) of each sub-array
const firstColumn = _.pluck(matrix, 0);
console.log(firstColumn); // Output: [10, 40, 70]Example 3: Handling Missing Properties#
If some elements lack the target property, _.pluck returns undefined for those entries:
const products = [
{ id: 1, name: 'Laptop', price: 999 },
{ id: 2, name: 'Mouse' }, // No 'price' property
{ id: 3, name: 'Keyboard', price: 49 }
];
const prices = _.pluck(products, 'price');
console.log(prices); // Output: [999, undefined, 49]Common Use Cases#
_.pluck shines in scenarios where you need to quickly extract a single property from a collection. Common use cases include:
- Data Extraction: Extracting IDs, names, or emails from API responses (e.g.,
_.pluck(apiResponse.users, 'id')). - Chart Data Preparation: Extracting x/y values from a dataset for visualization (e.g.,
_.pluck(salesData, 'revenue')). - Filtering + Extraction: Combining with
_.filterto extract properties from a subset of the collection:const adults = _.filter(users, user => user.age >= 18); const adultNames = _.pluck(adults, 'name'); // Extract names of adults only - Simplifying Reducers: Extracting properties before aggregating data (e.g., summing ages:
_.sum(_.pluck(users, 'age'))).
Common Practices#
-
Chaining with Underscore: Use
_.chainto combine_.pluckwith other Underscore functions for cleaner code:const activeUserEmails = _.chain(users) .filter(user => user.isActive) // Filter active users .pluck('email') // Extract emails .value(); // Get the final array -
Handling Nested Properties (Indirectly):
_.pluckdoes not support nested properties (e.g.,user.address.city), but you can use_.mapwith_.property(another Underscore utility) as a workaround:const userCities = _.map(users, _.property('address.city')); // Equivalent to _.pluck for nested properties
Best Practices#
-
Prefer Readability: Use
_.pluckwhen it makes code more concise than a manual_.mapor nativeArray.map. For example:// Good: Concise and readable _.pluck(users, 'name'); // Less concise (but equivalent) _.map(users, user => user.name); -
Beware of
undefinedValues: If some elements may lack the target property, handleundefinedexplicitly (e.g., with_.compactto removeundefinedentries):const validPrices = _.compact(_.pluck(products, 'price')); // Removes undefined -
Avoid Overusing for Non-Object Collections:
_.pluckis designed for objects. For primitives (e.g.,[1, 2, 3]), extracting properties liketoStringwill return function references, not values:_.pluck([1, 2, 3], 'toString'); // [Function: toString, Function: toString, Function: toString] -
Type Check Inputs: Ensure
listis a valid collection (array/object) andpropertyNameis a string/number to avoid unexpected behavior.
Limitations and Edge Cases#
- No Nested Property Support:
_.pluck('user.address.city')will not work. Use_.mapwith_.propertyinstead (as shown earlier). - Functions as Values: If the property is a function,
_.pluckreturns the function itself, not its result:const items = [{ getValue: () => 42 }, { getValue: () => 99 }]; _.pluck(items, 'getValue'); // [Function, Function] (not [42, 99]) - Empty or Non-Collection Inputs: If
listisnullorundefined,_.pluckreturns an empty array:_.pluck(null, 'name'); // [] _.pluck(undefined, 'age'); // [] - Non-Object Elements: If elements are primitives (e.g., strings, numbers), accessing properties returns
undefined(unless the primitive has the property, like'hello'.length):_.pluck(['hello', 'world'], 'length'); // [5, 5] (works for string length) _.pluck([123, 456], 'length'); // [undefined, undefined] (numbers have no length)
Alternatives to _.pluck#
With the rise of modern JavaScript (ES6+), native methods and other libraries offer alternatives to _.pluck:
1. Native Array.map#
For arrays, Array.map is a built-in alternative with no external dependencies:
const userNames = users.map(user => user.name); // Equivalent to _.pluck(users, 'name')2. Lodash’s _.map with _.property#
Lodash (a popular alternative to Underscore) deprecated _.pluck in favor of _.map with _.property:
import { map, property } from 'lodash';
const userNames = map(users, property('name'));3. Ramda’s pluck#
Ramda, a functional programming library, offers a pluck function with similar behavior:
import { pluck } from 'ramda';
const userNames = pluck('name')(users); // Curried versionConclusion#
_.pluck is a versatile utility for extracting property values from collections, simplifying code and improving readability. While modern JavaScript and libraries like Lodash offer alternatives, _.pluck remains valuable in Underscore.js codebases for its brevity and focus on the common task of property extraction.
By understanding its syntax, use cases, and limitations, you can leverage _.pluck to write cleaner, more maintainable code when working with arrays and objects.