如何从嵌套对象数组中获取目标节点的全路径指定属性值
嵌套对象数组路径查找实现
需求说明
我有一个多层嵌套的对象数组,每个对象可能包含children子节点。
示例数据
const data = [ { id: 1, name: 'parent 1', children: [ { id: 'c1', name: 'child 1', children: [ { id: 'g1', name: 'grand 1', children: [], }, ], }, ], }, { id: 2, name: 'parent 2', children: [ { id: 2, name: 'c1', children: [], }, ], }, { id: 3, name: 'parent 3', children: [] }, ];
期望效果
当搜索id为'g1'时,返回从根节点到匹配节点路径上所有节点的指定属性值组成的数组,遍历到匹配节点后立刻停止,无需遍历其他分支,示例返回:
const result = ['parent 1', 'c1', 'grand 1']
原有实现问题
你当前的代码仅能收集匹配节点本身的属性值,没有将上层父节点的属性加入结果,无法返回完整的层级路径。
修复后实现代码
/** * 查找嵌套数组中指定id节点的完整路径属性集合 * @param id 要搜索的目标id值 * @param items 嵌套对象数组 * @param key 要提取的属性名 * @returns 从根节点到匹配节点的属性值数组,未找到返回空数组 * @example findAll('g1', data, 'name') // 返回 ['parent 1', 'child 1', 'grand 1'] */ export function findAll(id: string, items: any[], key: string): string[] { for (const item of items) { // 当前节点匹配目标id,直接返回包含当前节点指定属性的数组 if (item.id === id) { return [item[key]] } // 存在子节点则递归搜索子节点分支 if (Array.isArray(item.children)) { const childPath = findAll(id, item.children, key) // 子分支找到匹配,将当前节点属性拼在路径开头向上返回 if (childPath.length) { return [item[key], ...childPath] } } } // 当前分支未找到匹配,返回空数组 return [] }
逻辑说明
- 遍历当前层级所有节点,匹配到目标id后直接向上返回,不会遍历其他冗余分支,满足提前停止的要求
- 子分支返回非空数组时说明匹配节点在该分支下,自动拼接当前节点属性形成完整路径
- 无额外第三方依赖,兼容空children、无children等边界场景
内容的提问来源于stack exchange,提问作者noxin D invictus
相关产品推荐
相关产品推荐

