在 lodash 中 reduce 后继续链

Continue chain after reduce in lodash

我想做如下的事情

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

然而,在 reduce 之后,链似乎断开了。

有没有办法从 reduce 返回的值继续链?

lodash 文档说 reduce() 不可链接。看这里: "The wrapper methods that are not chainable by default are: ... reduce" https://lodash.com/docs#_

reduce() 方法不能保证生成其他方法可以操作的集合(数组、对象或字符串),因此默认情况下它可以链接是没有意义的。

来自 lodash 对象的 lodash 文档 (_):

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

但是,您可以使用 _.chain() 明确强制执行链接。这将允许在 lodash 包装器中显式返回单个值和原语以继续链接。

所以您的代码可能如下所示:

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

_.chain() documentation