简体   繁体   中英

Continue chain after reduce in lodash

I want to do something like as follows

_(data)
  .map(() => /** ... */)
  .reduce(function (modifier, doc) {
    modifier.$set = modifier.$set || {};
    modifier.$set.names = doc.names;
    return modifier;
  }, {})
  .map(() => /** ... */)
  .flatten()

However, it appears that after reduce, the chain breaks.

Is there a way to continue the chain from the value returned by reduce?

reduce() method is not guaranteed to produce a collection (array, object, or string) upon which other methods could operate, therefore it makes no sense that it could be chainable by default.

From lodash documentation on lodash object ( _ ):

Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primitive value will automatically end the chain returning the unwrapped value.

_ documentation

You can however explicitly enforce chaining by using _.chain() . This would allow for single values and primitives to be explicitly returned within lodash wrapper for continued chaining.

So for your code that might look like:

_.chain(data)
  .map(() => /** ... */)
  .reduce(function (modifier, doc) {
    modifier.$set = modifier.$set || {};
    modifier.$set.names = doc.names;
    return modifier;
  }, {})
  .map(() => /** ... */)
  .flatten()

_.chain() documentation

The lodash docs say that reduce() is not chainable. See here: "The wrapper methods that are not chainable by default are: ... reduce" https://lodash.com/docs#_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM