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

使用Lodash过滤多维对象:多键多值过滤失效问题求助

解决Lodash过滤多维对象的问题

首先,我注意到你遇到的问题主要有两个核心关键点:

  • 你要过滤的是键为数字的对象,而Lodash的_.filter()默认是用来处理数组的,直接传入对象不会得到预期结果;
  • 你的条件里把数字类型的rating和字符串(比如'2')做匹配,类型不匹配导致判断失败。

第一步:把待过滤的对象转为数组

因为你的数据源是{ "0": {...}, "1": {...}, "2": {...} }这种结构,我们可以用Lodash的_.values()或者原生的Object.values()把它转换成数组,这样_.filter()就能正常遍历处理了。

第二步:修正条件的类型匹配问题

你的details.rating是数字类型(比如2.5、3、2),所以判断的时候要用数字而非字符串去匹配。

正确的实现示例

情况1:仅过滤rating为2或3的项

// 先把对象转成数组
const dataArray = _.values(yourData);
// 用Lodash过滤
const filteredData = _.filter(dataArray, item => [2, 3].includes(item.details.rating));
console.log(filteredData);

或者用Lodash内置的_.includes()更贴合工具库的用法:

const filteredData = _.filter(dataArray, item => _.includes([2, 3], item.details.rating));

情况2:结合多条件过滤(比如同时要求airConditioning为true、refundable为Yes)

const filteredData = _.filter(dataArray, item => {
  return _.includes([2, 3], item.details.rating) &&
         item.details.amenities.airConditioning &&
         item.rates.packages.some(pkg => pkg.refundable === 'Yes');
});

解释你之前的代码无效原因

  1. 第一个写法里,你在过滤条件对象中重复写了'details.rating',对象里重复的键会被最后一个覆盖,实际生效的只有'details.rating': '3',再加上用字符串匹配数字,自然找不到结果;
  2. 第二个写法里,你用['2', '3'].indexOf(item.details.rating),数组里是字符串类型,而item.details.rating是数字,类型不匹配导致indexOf返回-1,过滤结果为空;
  3. 最关键的是,你直接把对象传给了_.filter(),它无法正确遍历对象的value进行过滤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:22:16