_.forEach are frequently used functions when processing collections, and ES6 provides direct support for them:
_.map is more powerful, in that it works on objects, has iteratee / predicate shorthands, lazy evaluation, guards against null parameter, and has better performance.
To iterate over an object in ES6, there’re several approaches:
With Lodash, there’s a unified
_.forEach, for both array and object:
Although ES6 does provide
forEach for the newly added
Map type, it takes some effort to first convert an object into a
To extract some property from an array of objects:
This can be more helpful when it comes to complex objects:
As we can see, Lodash not only provides conveniet shorthands, it also guards against undefined values. For
_.filter, there’s also predicate shorthand. Here are some examples from Lodash documentation:
Here comes the fun part. Processing collections with chaining, lazy evaluation, along with short, easy-to-test functions, is quite popular these days. Most Lodash functions regarding collections can be chained easily. The following is a wordcount example:
ES6 introduces some useful syntaxes like destructuring, spread and arrow function, which can be used to replace a lot of Lodash functions. For instance:
For collection related operations, I prefer Lodash functions for they are more concise and can be chained; for functions that can be rewritten by arrow function, Lodash still seems more simple and clear. And according to some arguments in the references, the currying, operators and fp style from Lodash are far more useful in scenarios like function composition.