You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确使用lodash的flow方法结合find、get替代Ramda的pipe功能?

问题原因

Lodash 原生方法和 Ramda 方法的设计有两个核心差异,导致你写的代码无法运行:

  • Ramda 默认所有方法柯里化,且参数顺序为数据最后,所以你可以只传规则参数就把 R.find 直接塞进管道
  • Lodash 原生方法默认不柯里化,且参数顺序为数据优先,_.find 第一个参数需要传入要遍历的数组,直接只传回调会执行报错,也无法适配 _.flow 管道的参数传递规则
  • 额外小问题:_.flow 不需要把函数放到数组中包裹,直接按执行顺序传入多个函数参数即可

解决方案

方案1:使用原生 Lodash 手动适配

手动给管道内的函数加一层箭头函数,承接上一级传递进来的数据参数:

const test = aRouteId &&
    _.flow(
      // 第一个入参就是管道输入的 allSelectedRoutes
      (allRoutes) => _.find(allRoutes, (r: any) => r['pointIndex'] === aTerraIndex && r['routeIndex'] === aRouteIndex),
      // 入参是 find 返回的匹配项
      (matchedRoute) => _.get(matchedRoute, 'wayOfLiving')
    )(allSelectedRoutes)

方案2:使用 lodash/fp 版本(更贴近 Ramda 写法)

lodash/fp 是 Lodash 官方提供的函数式编程适配版本,所有方法默认柯里化、参数顺序改为数据最后,写法和 Ramda 几乎一致:

// 先引入 lodash/fp 的对应方法
import { flow, find, get } from 'lodash/fp';

const test = aRouteId &&
    flow(
      find((r: any) => r['pointIndex'] === aTerraIndex && r['routeIndex'] === aRouteIndex),
      get('wayOfLiving')
    )(allSelectedRoutes)

内容的提问来源于stack exchange,提问作者bazmexes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 12:09:04