如何使用对象数组对另一对象数组进行部分匹配搜索
对象数组的部分匹配搜索实现
问题描述
我有如下对象数组:
[ { "prop1": "value1", "prop2": "value1", "check": { "gender": ['male'], "office": ['London','New York'] } }, { "prop1": "value2", "prop2": "value2", "check": { "gender": ['female'], "office": ['Berlin', 'New York'] } } ]
需要实现一个搜索功能:传入一个条件对象,与数组元素的check属性做部分匹配,具体要求:
- 传入
{"office": ['New York']}时返回两个元素; - 传入
{"gender": ['male'], "office": ['London']}时仅返回第一个元素; - 传入
{"gender": ['female'], "office": ['London', 'Berlin']}时返回第二个元素。
目前只能判断对象完全相等,不知道怎么实现这种部分匹配。
解决方案
核心逻辑是:条件对象的每一个键对应的数组元素,必须全部存在于目标元素check对应键的数组中。基于这个逻辑封装通用过滤函数:
function filterByCheckCondition(items, condition) { return items.filter(item => { // 遍历条件的所有属性 for (const key in condition) { const conditionVals = condition[key]; const itemVals = item.check[key] || []; // 检查条件里的所有值是否都在目标数组中 const isMatch = conditionVals.every(val => itemVals.includes(val)); // 只要有一个属性不满足,就排除当前元素 if (!isMatch) return false; } // 所有条件都满足,保留元素 return true; }); }
测试验证
用你的测试场景验证函数效果:
const data = [ { "prop1": "value1", "prop2": "value1", "check": { "gender": ['male'], "office": ['London','New York'] } }, { "prop1": "value2", "prop2": "value2", "check": { "gender": ['female'], "office": ['Berlin', 'New York'] } } ]; // 测试场景1 const res1 = filterByCheckCondition(data, {"office": ['New York']}); console.log(res1.length); // 输出2 // 测试场景2 const res2 = filterByCheckCondition(data, {"gender": ['male'], "office": ['London']}); console.log(res2.length); // 输出1 // 测试场景3 const res3 = filterByCheckCondition(data, {"gender": ['female'], "office": ['London', 'Berlin']}); console.log(res3.length); // 输出1
灵活扩展
- 如果需要实现任意匹配(条件数组中只要有一个元素匹配即可),只需把
every替换为some; - 若条件中的键可能不存在于
check中,可以添加判断逻辑(比如默认不匹配,或默认匹配); - 对于非数组类型的条件值(比如
gender: 'male'),可以统一转成数组处理,让函数兼容性更好:// 新增处理非数组的逻辑 const conditionVals = Array.isArray(condition[key]) ? condition[key] : [condition[key]];
内容的提问来源于stack exchange,提问作者user3174311
相关产品推荐
相关产品推荐

