Issue
This Content is from Stack Overflow. Question asked by Mohanraj G
I have a array of objects that I pass through lodash chain to get the desired output.
But I want to make the code modular so instead of using _
. I want to import the specific functions to reduce import size, I searched through lodash docs, but couldn’t found anything useful.
import _ from 'lodash'
let TransactionList = _(TransactionData)
.groupBy('hash')
.map(_.spread(_.merge))
.value()
I tried this but this doesn’t work either.
import { flow, groupBy, map, merge, spread } from 'lodash'
let TransactionList = flow(
groupBy('hash'),
map(spread(merge))
)(TransactionData)
Solution
Lodash’s functions are not curried, and the functions expect the data as the 1st parameter. To work with flow, you need to wrap functions that expect more then one parameter with an arrow function, and pass the data (arr
or groups
in this example) by yourself:
import { flow, groupBy, map, merge, spread } from 'lodash'
const TransactionList = flow(
arr => groupBy(arr, 'hash'),
groups => map(groups, spread(merge))
)(TransactionData)
Lodash has a deprecated functional version (lodash/fp) that solved this issue, and when using lodash/fp your code (with a minor change) would work:
import { flow, groupBy, map, mergeAll } from 'lodash'
const TransactionList = flow(
groupBy('hash'),
map(mergeAll)
)(TransactionData)
This Question was asked in StackOverflow by Mohanraj G and Answered by Ori Drori It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.