可以使用递归实现树形结构遍历并增加 path 属性。假设树形结构如下:

const tree = {
  name: 'root',
  children: [
    {
      name: 'child1',
      children: [
        {
          name: 'grandchild1',
          children: []
        },
        {
          name: 'grandchild2',
          children: [
            {
              name: 'great-grandchild1',
              children: []
            }
          ]
        }
      ]
    },
    {
      name: 'child2',
      children: []
    }
  ]
};

我们需要遍历这个树形结构并为每个节点增加 path 属性。path 属性的值为一个字符串,表示该节点在树形结构中的层级关系。例如,根节点的 path 为 '0.0',第一个子节点的 path 为 '1.0',第一个孙子节点的 path 为 '1.1.0',以此类推。

以下是一个实现此功能的递归函数:

function addPath(tree, path = '0') {
  tree.path = path;
  if (tree.children && tree.children.length > 0) {
    for (let i = 0; i < tree.children.length; i++) {
      const child = tree.children[i];
      const childPath = `${path}.${i}`;
      addPath(child, childPath);
    }
  }
}

这个函数接受两个参数:树形结构和当前节点的 path。在递归调用时,我们将当前节点的 path 传递给它的子节点,并在该节点的 path 后面添加一个 'i',其中 'i' 表示该子节点在父节点的 children 数组中的索引。

为了使用这个函数,我们只需要调用它并传递树形结构作为参数:

addPath(tree);
console.log(tree);

这将输出如下结果:

{
  name: 'root',
  children: [
    {
      name: 'child1',
      children: [
        {
          name: 'grandchild1',
          children: [],
          path: '0.1.0'
        },
        {
          name: 'grandchild2',
          children: [
            {
              name: 'great-grandchild1',
              children: [],
              path: '0.1.1.0'
            }
          ],
          path: '0.1.1'
        }
      ],
      path: '0.1'
    },
    {
      name: 'child2',
      children: [],
      path: '0.2'
    }
  ],
  path: '0'
}

可以看到,每个节点都被增加了 path 属性,表示它在树形结构中的层级关系。

ES6 树形结构递归遍历添加路径属性

原文地址: https://www.cveoy.top/t/topic/oPfn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录