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

嵌套filter返回空数组,如何正确筛选包含指定location的外层对象?

问题原因

外层filter方法的回调需要返回布尔值来判断当前元素是否要被保留,你内层用filter返回的是符合条件的子元素组成的数组,这种写法不符合逻辑要求,也会出现判断异常,最终导致结果不符合预期。

修正方法

将内层的filter替换为some方法,some会在内层数组存在至少一个符合条件的元素时返回布尔值true,正好匹配你的筛选需求。
修正后代码如下:

const locations = ["Los Angeles", "Chicago"];
// data为你的原始数据源
const filteredData = data.filter((outerItem) =>
  outerItem.data.some((innerItem) => locations.includes(innerItem.location))
);
return filteredData;

如果需要兼容内层元素可能不存在location字段的异常场景,可以调整判断逻辑为:

outerItem.data.some((innerItem) => innerItem?.location && locations.includes(innerItem.location))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:30:01