如何在含嵌套对象数组的对象数组中按多属性动态查询
解决方案
针对你需要从包含嵌套filter数组的主对象数组中,根据动态查询对象筛选主对象的需求,可以用以下JavaScript实现:
步骤1:定义主数据数组
const mainArray = [ { property1: 'test', property2: 'test', filter: [ { fil1: 1, fil2: 2, fil3: 3 }, { fil1: 56, fil2: 3, fil3: 34 }, { fil1: 23, fil2: 88, fil3: 6 } ] }, { property1: 'test2', property2: 'test2', filter: [ { fil1: 44, fil2: 5, fil3: 99 }, { fil1: 333, fil2: 7, fil3: 888 }, { fil1: 10, fil2: 5, fil3: 688 } ] } ];
步骤2:编写匹配验证函数
这个函数负责检查单个filter对象是否完全匹配查询对象的所有键值对:
function matchesQuery(obj, query) { const queryKeys = Object.keys(query); return queryKeys.every(key => obj.hasOwnProperty(key) && obj[key] === query[key]); }
步骤3:编写主查询函数
遍历主数组,筛选出其filter数组中至少存在一个匹配对象的主对象:
function findMatchingMainObjects(mainArray, query) { return mainArray.filter(mainObj => { return mainObj.filter.some(filterObj => matchesQuery(filterObj, query)); }); }
测试示例
- 查询
{fil2:2,fil3:3}:const result1 = findMatchingMainObjects(mainArray, { fil2: 2, fil3: 3 }); console.log(result1); // 返回第一个主对象 - 查询
{fil1:56,fil2:3}:const result2 = findMatchingMainObjects(mainArray, { fil1: 56, fil2: 3 }); console.log(result2); // 返回第一个主对象 - 查询单个属性
{fil2:5}:const result3 = findMatchingMainObjects(mainArray, { fil2: 5 }); console.log(result3); // 返回第二个主对象
逻辑说明
matchesQuery通过every方法确保查询对象的所有属性都能在目标filter对象中找到对应且相等的值,支持任意数量的查询属性。findMatchingMainObjects结合filter和some方法,快速定位符合条件的主对象:some只要找到一个匹配的filter对象,就会保留当前主对象。
内容的提问来源于stack exchange,提问作者Gia Nebieridze
相关产品推荐
相关产品推荐

