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

使用Lodash chain与filter未返回过滤结果的问题排查

问题诊断与修复方案

我一眼就看出两个关键问题导致你没得到预期结果:

1. 你输出的是原始数组,不是过滤后的结果

你代码里console.log(quoteList)打印的是未经过任何处理的原始数组,自然会显示全部2个对象。你应该打印的是链式调用处理后的QuoteSlides变量。

2. Lodash链式调用缺少终止方法

Lodash的chain()会返回一个包装对象,所有的操作都是延迟执行的,必须调用.value()(或者新版本里的.valueOf()、.toJSON())来触发执行,才能得到最终的过滤结果。

修正后的代码

let quoteList = shipment.quotes
const QuoteSlides = _.chain(quoteList)
  .filter(['state', 'accepted'])
  .value() // 关键:添加这个方法获取最终结果

console.log(QuoteSlides) // 现在打印的是过滤后的数组

额外说明

如果你的Lodash版本比较新(v4+),其实也可以不用chain(),直接用流式调用,更简洁:

const QuoteSlides = _.filter(quoteList, ['state', 'accepted'])
console.log(QuoteSlides)

这种方式不需要额外调用.value(),直接返回处理后的数组,对于简单的过滤场景更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:45:10