如何在含嵌套子对象数组的对象数组中深度查找对象?
嵌套对象数组的递归查找解决方案
嘿,这个问题我之前也碰到过!处理嵌套对象数组的查找,递归绝对是最简便的方案之一,它能帮你逐层遍历所有嵌套的子数组,不会漏掉任何一层。下面我给你分享两种实用的实现:一种找第一个符合条件的对象,另一种找所有符合条件的对象。
先看一个典型的嵌套对象数组示例
假设你的数据结构是这样的(如果和你的实际结构不同,只需要调整嵌套字段名即可):
const data = [ { id: 1, name: "父节点1", children: [ { id: 11, name: "子节点1-1" }, { id: 12, name: "子节点1-2", children: [{ id: 121, name: "孙节点1-2-1" }] } ] }, { id: 2, name: "父节点2" } ];
方案1:查找第一个符合条件的对象
这个函数会递归遍历整个结构,找到第一个满足条件的对象就返回:
function findNestedItem(arr, condition, nestedKey = 'children') { // 遍历当前层级的每个对象 for (const item of arr) { // 检查当前对象是否符合查找条件 if (condition(item)) { return item; } // 如果当前对象有嵌套子数组,递归进入子层级查找 if (item[nestedKey] && Array.isArray(item[nestedKey])) { const result = findNestedItem(item[nestedKey], condition, nestedKey); // 递归找到结果的话,立即返回 if (result) { return result; } } } // 遍历完所有层级都没找到,返回null return null; }
使用示例
比如要查找id为121的对象:
const target = findNestedItem(data, item => item.id === 121); console.log(target); // 输出:{ id: 121, name: "孙节点1-2-1" }
方案2:查找所有符合条件的对象
如果需要把所有匹配的对象都找出来,可以用这个收集型的递归函数:
function findAllNestedItems(arr, condition, nestedKey = 'children', result = []) { for (const item of arr) { // 符合条件就加入结果数组 if (condition(item)) { result.push(item); } // 递归遍历子数组,把匹配项也收集进来 if (item[nestedKey] && Array.isArray(item[nestedKey])) { findAllNestedItems(item[nestedKey], condition, nestedKey, result); } } return result; }
使用示例
比如查找所有名称包含“节点”的对象:
const allTargets = findAllNestedItems(data, item => item.name.includes("节点")); console.log(allTargets); // 会返回所有符合条件的父、子、孙节点对象
为什么这个方案好用?
- 灵活性高:可以自定义查找条件(比如根据
id、name或者其他字段),也可以指定嵌套字段名(如果你的子数组不叫children,改成你自己的字段就行) - 适配任意嵌套深度:不管你的数据嵌套了多少层,递归都会一层层钻进去找,不会遗漏
- 代码简洁易懂:逻辑清晰,后续维护也方便
内容的提问来源于stack exchange,提问作者otto
相关产品推荐
相关产品推荐

