JavaScript如何遍历嵌套对象数组实现包含子级匹配的模糊搜索
解决方案
实现逻辑
- 统一将关键词和待匹配文本转为大写,避免大小写敏感问题
- 遍历数组每一项,同时校验顶层
entry字段是否匹配、子项entry字段是否存在匹配 - 支持两种输出模式:保留完整顶层对象结构、仅保留匹配的子项,可通过参数灵活切换
- 操作过程中生成新对象,避免修改原数组
完整实现代码
/** * 嵌套对象数组筛选函数 * @param {Array} arr 待筛选的原数组 * @param {String} keyword 搜索关键词 * @param {Boolean} keepFullChildren 是否保留完整children数组,默认false * @returns {Array} 筛选后的结果数组 */ function filterNestedArray(arr, keyword, keepFullChildren = false) { const formattedKeyword = keyword.toUpperCase(); return arr.reduce((result, currentItem) => { // 校验顶层entry是否匹配 const isTopMatch = currentItem.entry.toUpperCase().includes(formattedKeyword); // 筛选出children中匹配的子项 const matchedChildren = currentItem.children.filter(child => child.entry.toUpperCase().includes(formattedKeyword) ); // 只要顶层匹配或存在匹配子项,就保留当前项 const hasValidMatch = isTopMatch || matchedChildren.length > 0; if (hasValidMatch) { let processedItem; if (keepFullChildren) { // 保留完整结构时浅拷贝原对象(深层结构可替换为深拷贝方法) processedItem = {...currentItem}; } else { // 仅保留匹配子项时替换children字段 processedItem = {...currentItem, children: matchedChildren}; } result.push(processedItem); } return result; }, []); }
场景调用示例
场景1:搜索Tim,返回完整顶层对象
const result1 = filterNestedArray(array, 'Tim', true);
返回结果和给出的场景1预期完全一致。
场景2:搜索John,仅保留匹配子项
const result2 = filterNestedArray(array, 'John');
返回结果和给出的场景2预期完全一致。
场景3:搜索Steven,仅保留匹配子项
const result3 = filterNestedArray(array, 'Steven');
注:给出的场景3示例输出中额外包含了John Jr属于笔误,实际调用后每个匹配项的children仅会保留Steven Jr子项,符合筛选逻辑。
扩展说明
如果你的children是深层嵌套结构(子项还包含children字段),只需要将上述代码中筛选matchedChildren的逻辑改为递归调用即可。
如果对象结构较复杂,可将浅拷贝逻辑替换为structuredClone(currentItem)等深拷贝实现,避免引用类型修改影响原数组。
内容的提问来源于stack exchange,提问作者user2824374
相关产品推荐
相关产品推荐

