JS深层嵌套数组对象中如何按指定key获取所有子节点key值
实现方法
直接用深度优先递归遍历即可,核心逻辑如下:
- 遍历整棵树形结构,匹配传入的目标key
- 找到匹配节点后,先存入当前节点的key,再递归遍历该节点下所有层级的子节点,把所有后代节点的key全部收集到结果中
- 支持同时传入多个目标key,自动收集所有匹配节点的自身+后代key,无嵌套层级限制
完整实现代码:
const data = [ { title: '0-0', key: '0-0', children: [ { title: '0-0-0', key: '0-0-0', children: [ { title: '0-0-0-0', key: '0-0-0-0' }, { title: '0-0-0-1', key: '0-0-0-1' }, { title: '0-0-0-2', key: '0-0-0-2' }, ], }, { title: '0-0-1', key: '0-0-1', children: [ { title: '0-0-1-0', key: '0-0-1-0' }, { title: '0-0-1-1', key: '0-0-1-1' }, { title: '0-0-1-2', key: '0-0-1-2' }, ], }, { title: '0-0-2', key: '0-0-2', }, ], }, { title: '0-1', key: '0-1', children: [ { title: '0-1-0-0', key: '0-1-0-0' }, { title: '0-1-0-1', key: '0-1-0-1' }, { title: '0-1-0-2', key: '0-1-0-2' }, ], }, { title: '0-2', key: '0-2', }, ]; function collectTargetKeys(tree, targetKeys) { const result = []; // 递归收集单个节点及其所有后代key const collectAllChild = (node) => { result.push(node.key); if (node.children?.length) { node.children.forEach(child => collectAllChild(child)); } }; // 深度遍历整棵树查找目标节点 const dfs = (nodeList) => { for (const node of nodeList) { if (targetKeys.includes(node.key)) { collectAllChild(node); } if (node.children?.length) { dfs(node.children); } } }; dfs(tree); return result; }
效果验证
传入示例参数测试:
const output = collectTargetKeys(data, ["0-0-0"]); console.log(output); // 打印结果:["0-0-0", "0-0-0-0", "0-0-0-1", "0-0-0-2"],和预期结果完全一致
补充说明:
- 传入多个目标key时可正常批量收集,比如传入
["0-0-1", "0-2"]会返回两个节点对应的所有自身+后代key - 无嵌套深度限制,无论节点藏在多少层children下都能正常匹配
- 叶子节点(无children属性)命中时只会返回自身key,符合预期逻辑
内容的提问来源于stack exchange,提问作者Joonen
相关产品推荐
相关产品推荐

