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?
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?
Share Improve this question edited Oct 8, 2015 at 19:42 corvid asked Oct 8, 2015 at 19:37 corvidcorvid 11.2k12 gold badges71 silver badges134 bronze badges 4-
so what does the
reduce
return? No way for us to reproduce your issue. A demo that replicates it would help – charlietfl Commented Oct 8, 2015 at 19:40 -
something that looks like
{ $set: { names: [ 'alex', 'jeff' ] } }
– corvid Commented Oct 8, 2015 at 19:42 - yeah, that's just an example though. I mean I want to continue with the chain as this object – corvid Commented Oct 8, 2015 at 19:43
- start a new chain, reduce returns it own non-array thing, which can't be chained... – dandavis Commented Oct 8, 2015 at 19:45
2 Answers
Reset to default 7reduce()
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./docs#_