Lodash map: How to Transform Collections
The _.map method in the Lodash JavaScript library is a
utility designed to transform collections by applying an iteratee
function to each element, producing a new array of modified values.
Unlike the native JavaScript Array.prototype.map(),
Lodash’s implementation is versatile enough to handle arrays, objects,
and strings, while offering built-in safeguards against
null or undefined inputs. This article covers
the syntax of _.map, how it processes different collection
types, its built-in shorthand iterators, and its advantages over native
JavaScript methods.
Basic Syntax and Parameters
The general syntax for the _.map method is:
_.map(collection, [iteratee=_.identity])collection: The data structure to iterate over (an array, object, or string).iteratee: The function invoked per iteration. It receives three arguments:(value, index|key, collection). By default, this is the identity function, which simply returns the value unchanged.
Transforming Arrays
When applied to an array, _.map acts similarly to the
native array mapping method, iterating through elements by their index
and generating a new array containing the returned values:
const numbers = [1, 2, 3, 4];
const doubled = _.map(numbers, (n) => n * 2);
console.log(doubled); // Output: [2, 4, 6, 8]Transforming Objects
A major advantage of _.map is its native support for
plain JavaScript objects. When given an object, it iterates over its
enumerable properties and passes the property value, the key, and the
original object to the iteratee. The output is always returned as a flat
array:
const userAges = {
alice: 25,
bob: 30,
charlie: 35
};
const userLabels = _.map(userAges, (age, name) => `${name} is ${age} years old`);
console.log(userLabels);
// Output: ['alice is 25 years old', 'bob is 30 years old', 'charlie is 35 years old']Shorthand Iteratee Syntaxes
Lodash provides convenient shorthands that allow you to transform collections without writing full callback functions:
Property Shorthand
Passing a string as the iteratee acts as a "pluck" operation, extracting the value of that specific property from each object in the collection:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const names = _.map(users, 'name');
console.log(names); // Output: ['Alice', 'Bob']MatchesProperty and Matches Shorthands
You can pass an array defining a key-value pair or an object to perform deep property matching, which returns an array of booleans:
const items = [
{ product: 'Laptop', inStock: true },
{ product: 'Phone', inStock: false }
];
// MatchesProperty shorthand
const stockStatus = _.map(items, ['inStock', true]);
console.log(stockStatus); // Output: [true, false]Key Differences from Native JavaScript
- Type Flexibility: Native
maponly exists on theArrayprototype. Lodash_.mapworks seamlessly across arrays, objects, and strings. - Defensive Programming: Calling native
.map()onnullorundefinedthrows aTypeError. Lodash gracefully handles non-collection values and returns an empty array ([]). - Conciseness: The property shorthand removes the
need to write repetitive arrow functions (e.g.,
item => item.property) when projecting specific keys out of complex datasets.