Lodash's `map()` Function

Apr 8, 2020

Given an array arr and a function fn, Lodash's map() function returns an array containing the return values of fn() on every element in the array.

const arr = [1, 2, 3, 4];

_.map(arr, v => v * 2); // [2, 4, 6, 8]

On Arrays of Objects

Given an array of objects, you can pass a string as fn instead of a function to get array containing each object's value for the property fn.

const arr = [
  { firstName: 'Will', lastName: 'Riker', rank: 'Commander' },
  { firstName: 'Beverly', lastName: 'Crusher', rank: 'Commander' },
  { firstName: 'Wesley', lastName: 'Crusher', rank: 'Ensign' }
];

_.map(arr, 'firstName'); // ['Will', 'Beverly', 'Wesley']
// Equivalent:
_.map(arr, v => v.firstName); // ['Will', 'Beverly', 'Wesley']

On Objects

You can also call _.map() on an object. _.map(obj, fn) behaves like _.map(Object.values(obj), fn).

const obj = {
  one: 1,
  two: 2,
  three: 3,
  four: 4
};

_.map(obj, v => v * 2); // [2, 4, 6, 8]

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Lodash Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!