You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求ES6+实现:获取自定义JSON结构的所有节点路径方案

提取嵌套节点的全路径字符串数组解决方案

核心实现(ES6+)

我们可以通过递归遍历的方式,维护当前节点的父路径,逐个生成每个节点的完整路径字符串:

const generateNodePaths = (nodes, parentPath = '') => {
  let paths = [];
  for (const node of nodes) {
    // 生成当前节点的完整路径
    const currentPath = parentPath ? `${parentPath}.${node.name}` : node.name;
    paths.push(currentPath);
    // 如果存在子节点,递归处理并合并结果
    if (node.children?.length) {
      paths = [...paths, ...generateNodePaths(node.children, currentPath)];
    }
  }
  return paths;
};

示例验证

修正输入为合法的JavaScript结构后:

const inputNodes = [
  { name: 'name1' },
  { name: 'name2' },
  { name: 'name3', children: [
    { name: 'name3Child1' },
    { name: 'name3Child2' },
    { name: 'name3Child3', children: [{ name: 'name3Child3Child1' }] }
  ] },
  { name: 'name4' },
];

调用函数后得到的结果与预期完全一致:

const result = generateNodePaths(inputNodes);
console.log(result);
// 输出:
// [
//   'name1',
//   'name2',
//   'name3',
//   'name3.name3Child1',
//   'name3.name3Child2',
//   'name3.name3Child3.name3Child3Child1',
//   'name4'
// ]

实现说明

  • 用递归遍历处理任意层级的嵌套children数组,无需提前定义嵌套深度
  • 利用ES6可选链操作符?.安全判断子节点是否存在,避免空值报错
  • 通过扩展运算符...合并当前节点路径与子节点递归返回的路径数组,写法简洁高效
  • 支持初始传入父路径参数,可灵活处理从某个中间节点开始生成路径的场景

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:09:30