JS树结构的遍历、创建

这样树结构的数组:

     
let tree =[
     {id: '1',
        title: '节点1',
        children: [
          {
            id: '1-1',
            title: '节点1-1',
            children: [
              {
                id: '1-1-1',
                title: '节点1-1-1'
              },]
          },
          {
            id: '1-2',
            title: '节点1-2'
          }
        ]
      },
      {
        id: '2',
        title: '节点2',
        children: [
          {
            id: '2-1',
            title: '节点2-1'
          }
        ]
      }
    ]
    

我想把其中的某项取出创建新的数组,结构不变,例如这样

  getTree =[
     {
        title: '节点1',
        children: [
          {
            title: '节点1-1',
            children: [
              {
                title: '节点1-1-1'
              },]
          },
          {
            title: '节点1-2'
          }
        ]
      },
      {
        title: '节点2',
        children: [
          {
            title: '节点2-1'
          }
        ]
      }
    ]
    

不知道怎么写,不知道描述清楚没,我是新手,不耻下问啊...

阅读 4.6k
2 个回答

你可以先了解一下什么是 递归
这个需求通过递归可以很轻易实现

function getTree(ary) {
  return ary.map(v => {
    const item = {
      title: v.title,  //这是创建的新对象 根据需要的键随意更改
    };
    if (v.children) item.children = getTree(v.children);
    return item;
  });
}
const newTree = getTree(tree);
console.log(newTree)

貌似两个数组一样的,就是id没了而已~

推荐问题