Most Lodash methods that accept a function — map, filter, find, sortBy, groupBy, and others — also accept three shorthand forms in place of that function. Each parameter in this documentation is converted through _.iteratee internally, so the shorthand behaves the same wherever a method's parameter list shows an [iteratee=identity], [predicate=identity], or [paths] default.
var users = [
{ user: 'barney', age: 36, active: true },
{ user: 'fred', age: 40, active: false }
];Property shorthand
A string is treated as a property path. _.map(users, 'user') is shorthand for map(users, function (o) { return o.user; }):
_.map(users, 'user');
// => ['barney', 'fred']This also works for nested paths, using the same dot-and-bracket syntax as _.get:
var objects = [{ a: { b: 2 } }, { a: { b: 1 } }];
_.map(objects, 'a.b');
// => [2, 1]Matches shorthand
An object is treated as a partial-match predicate. _.filter(users, { active: false }) is shorthand for filter(users, function (o) { return isMatch(o, { active: false }); }):
_.filter(users, { active: false });
// => [{ user: 'fred', age: 40, active: false }]Matches-property shorthand
A [path, value] pair is shorthand for matching one property to one value. _.find(users, ['active', false]) is shorthand for find(users, function (o) { return o.active === false; }):
_.find(users, ['active', false]);
// => { user: 'fred', age: 40, active: false }Write the equivalent function explicitly when you need one
Use _.property, matches, and matchesProperty to build the same function shorthand produces, when you want to reuse it or pass it somewhere that does not run it through iteratee:
var getUser = _.property('user');
_.map(users, getUser);
// => ['barney', 'fred']Watch for methods that forward extra arguments
Some native functions accept more parameters than their first — parseInt(string, radix) is the common case. Because _.map invokes its iteratee with (value, index, collection), passing parseInt directly can produce unexpected results once index lands in the radix position:
_.map(['6', '8', '10'], parseInt);
// => [6, NaN, 2] (index 1 and 2 are used as parseInt's radix argument)Wrap the function to control how many arguments it receives, using _.ary, or use the property shorthand instead when you don't need extra arguments:
_.map(['6', '8', '10'], _.ary(parseInt, 1));
// => [6, 8, 10]A number of lodash methods — including ary, chunk, range, sortBy, template, trim, and words — are documented as "guarded" specifically so they are safe to pass directly as an iteratee to every, filter, map, mapValues, reject, and some. Check a method's own reference entry for its "guarded methods" note before relying on this.
Next steps
- See the full parameter and return signature for every method in the API reference.
- Combine shorthands with a chain sequence to keep a multi-step transformation readable.