简体   繁体   English

在lodash减少后继续链

[英]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返回的值继续链?

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

From lodash documentation on lodash object ( _ ): 从关于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 _文档

You can however explicitly enforce chaining by using _.chain() . 但是,您可以使用_.chain()显式强制链接。 This would allow for single values and primitives to be explicitly returned within lodash wrapper for continued chaining. 这将允许在lodash包装器中显式返回单个值和基元以继续链接。

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 _.chain()文档

The lodash docs say that reduce() is not chainable. lodash文档说reduce()不是可链接的。 See here: "The wrapper methods that are not chainable by default are: ... reduce" https://lodash.com/docs#_ 请参见此处:“默认情况下不可链接的包装器方法是:... reduce” https://lodash.com/docs#_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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