Home > OS >  How to convert Lodash chain to modular imports
How to convert Lodash chain to modular imports

Time:09-19

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)

CodePudding user response:

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)

CodePudding user response:

Regarding only importing specific functions, you could use lodash-es, the Lodash library exported as ES modules.

For example:

import { pad, toUpper } from 'lodash-es';

console.log(pad(toUpper('hello world'), 17, '*'));  // ***HELLO WORLD***
  • Related