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

如何正确过滤满足嵌套数组指定数值条件的对象数组?

如何正确过滤包含嵌套数组的对象数组

嘿,我明白你遇到的问题了!你之前的代码只应用了第一个过滤条件(tags[0].number > 10),但没加上第二个要求的tags[1].number < 20,这就是结果不符合预期的原因。

正确的过滤代码

首先,我们先明确你的初始状态:

const initialState = [
  { id: 1, name: 'Product A', image: 'pic-001.jpg', tags: [{ id: 1, number: 12 }, { id: 2, number: 10 }] },
  { id: 2, name: 'Product B', image: 'pic-002.jpg', tags: [{ id: 1, number: 0 }, { id: 2, number: 102 }] },
  { id: 3, name: 'Product C', image: 'pic-003.jpg', tags: [{ id: 1, number: 1202 }, { id: 2, number: 100 }] }
];

要同时满足两个过滤条件,你需要在filter的回调函数里用**逻辑与(&&)**把两个判断连接起来,确保两个条件都成立才保留对象:

const filteredProducts = initialState.filter(e => {
  return e.tags[0].number > 10 && e.tags[1].number < 20;
});

console.log(filteredProducts);

结果验证

运行这段代码后,你会得到唯一符合条件的对象:

[
  { id: 1, name: 'Product A', image: 'pic-001.jpg', tags: [{ id: 1, number: 12 }, { id: 2, number: 10 }] }
]

因为只有Product A同时满足tags[0].number > 10(12>10)和tags[1].number < 20(10<20)这两个条件。

额外的健壮性建议

如果你的数组里可能存在tags元素不足2个的对象,为了避免出现Cannot read properties of undefined的错误,可以在判断前先检查tags的长度:

const filteredProducts = initialState.filter(e => {
  return e.tags.length >= 2 && e.tags[0].number > 10 && e.tags[1].number < 20;
});

这样就能确保只有包含至少两个标签的对象才会进入后续的条件判断,避免意外报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:09:11