如何利用多条件数组过滤对象数组中指定字段的匹配项?
问题描述
现有如下JSON数据:
[ { "name": "Enterprise Networking", "technology": "Networking" }, { "name": "Enterprise Networking", "technology": "Networking" }, { "name": "Wireless Insights", "technology": "Mobility and Wireless" }, { "name": "Mobility Insights", "technology": "Mobility and Wireless" }, { "name": "Lock it down", "technology": "Security" }, { "name": "Collaboration", "technology": "Security" } ]
需要基于过滤条件数组(例如["Networking", "Security"]),筛选出technology字段匹配数组中任意值的对象,排除不匹配的条目。
已实现单条件过滤:
result = learningMapsDataObj.filter(el => el.Technology === filter3[0].value);
尝试用循环方法实现多条件过滤但失败:
result = learningMapsDataObj.filter(el => el.Technology === myloopingArrCheckFunction(el.technology, filters3));
解决方案
方法1:使用数组includes方法(最简洁)
直接利用数组的includes方法判断当前元素的technology是否在过滤条件数组中,注意字段名大小写要统一(原始数据中是小写technology,之前的单条件代码写了大写Technology,这会导致匹配失败,必须修正)。
示例代码:
const filters = ["Networking", "Security"]; // 字段名与数据保持一致,用小写technology const result = learningMapsDataObj.filter(el => filters.includes(el.technology));
方法2:修正自定义循环函数
如果要通过自定义循环函数实现,需确保函数返回布尔值(表示是否匹配),而非将函数结果与字段值做全等比较。
先实现循环检查函数:
function myloopingArrCheckFunction(techValue, filters) { for (let filter of filters) { if (techValue === filter) { return true; // 找到匹配项,返回true } } return false; // 无匹配项,返回false }
再在过滤逻辑中直接使用函数返回值:
const filters3 = ["Networking", "Security"]; // 字段名统一为technology,直接用函数返回的布尔值判断 const result = learningMapsDataObj.filter(el => myloopingArrCheckFunction(el.technology, filters3));
关键注意事项
- 字段名大小写必须完全匹配:原始数据中字段为
technology(小写t),之前的代码误用Technology(大写T)会导致匹配失效,需修正。 - 过滤回调需返回布尔值:
filter方法的回调函数必须返回true/false来决定是否保留元素,之前的错误在于将函数结果与字段值做全等比较,逻辑不成立。
内容的提问来源于stack exchange,提问作者benishky
相关产品推荐
相关产品推荐

