Today I Learned

hashrocket A Hashrocket project

Iterating over objects in Lodash

Many of the Lodash collection functions iterate over either an object or an array. Somewhat unintuitively for me, when iterating over objects the first argument of the iteratee function is a value and the second argument is the key.

The documentation for Lodash lists the arguments for the iteratee in the description for each function. For collection functions that generally looks like this

The iteratee is invoked with three arguments:(value, index|key, collection).

By searching through the documentation for index|key you can find all the functions for which this is true.

Using a Lodash function that can return iterate over an object looks like this:

const result = _.map({a: 1, b: 2}, function(value, key) {
  return value + key;
});

// result is now ["a1", "b2"]

H/T Ryan Messner

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.