获取树结构所有路径?

有一下树形数据:

const data= [
  {
    label: 'Level one 1',
    children: [
      {
        label: 'Level two 1-1',
        children: [
          {
            label: 'Level three 1-1-1',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 2',
    children: [
      {
        label: 'Level two 2-1',
        children: [
          {
            label: 'Level three 2-1-1',
          },
        ],
      },
     
    ],
  }
]

期望输出所有叶子节点的路径:

["Level one 1 > Level two 1-1 > Level three 1-1-1", "Level one 2 > Level two 2-1 > Level three 2-1-1"]

阅读 3.3k
5 个回答

其实就是树的先序遍历

function preOrder(list, result=[], labels=[]) {
  return list.reduce((res,v) => {
    labels.push(v.label);
    if(v.children && v.children.length) preOrder(v.children, res, labels);
    else res.push(labels.join(' > '))
    labels.pop();
    return res;
  }, result)
}

preOrder(data)

使用reduce大法加递归可以搞定~


data.reduce((acc, cur) => {
  function concat(obj) {
    if (obj.hasOwnProperty('children')) {
      return obj['label'] + ' > ' + concat(obj['children'][0]);
    } else {
      return obj['label'];
    }
  }

  acc.push(concat(cur));
  return acc;
}, []);

写了个更简短的:

let f = (n, p = []) => n?.flatMap(i => f(i.children, [...p, i.label])) ?? p.join(' > ');

结果

[
  "Level one 1 > Level two 1-1 > Level three 1-1-1",
  "Level one 1 > Level two 1-1 > Level three 1-1-2",
  "Level one 2 > Level two 2-1 > Level three 2-1-1"
]

使用代码

const data = [
  {
    label: 'Level one 1',
    children: [
      {
        label: 'Level two 1-1',
        children: [
          {
            label: 'Level three 1-1-1',
          },
          {
            label: 'Level three 1-1-2',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 2',
    children: [
      {
        label: 'Level two 2-1',
        children: [
          {
            label: 'Level three 2-1-1',
          },
        ],
      },
    ],
  }
];

console.log(f(data));
const data= [
  {
    label: 'Level one 1',
    children: [
      {
        label: 'Level two 1-1',
        children: [
          {
            label: 'Level three 1-1-1',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 2',
    children: [
      {
        label: 'Level two 2-1',
        children: [
          {
            label: 'Level three 2-1-1',
          },
        ],
      },
     
    ],
  }
]
let html = ''
function fn (arr) {
  arr.forEach((v, i) => {
    fn1(v)
 })
}
function fn1 (item) {
  html = html + item.label + '>'
  item.children && fn(item.children)
}
fn(data)
let arr = []
arr.push(html)
console.log(arr)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏