js将树结构的列表转换为普通列表(不带children)

第一种:

function treeListToList(treeList) { // 将树结构的列表转换为普通列表
    let list = [];
    handleTreeList(treeList, list);
    return list
  }

function handleTreeList(treeList, list) { //处理数组
  if (!treeList || !treeList.length) {
    return
  }
  for (let i = 0; i < treeList.length; i++) {
    let currentRow = treeList[i];
    let newRow = JSON.parse(JSON.stringify(currentRow));
    newRow.children = undefined;
    list.push(newRow);
    handleTreeList(currentRow.children, list)
  }
}

第二种处理数组:

  const treeConvertArr = (tree,arr) =>{

      tree.map((item)=>{

        if(item.children){

          treeConvertArr(item.children,arr)

          delete item.children

        }

        arr.push(item)

      })

  }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
将一个列表转换树结构可以用递归来实现。我假设列表中的每个项都有一个 `id` 和一个 `parentId` 属性,`parentId` 指向其父级节点的 `id`。 下面是一个示例代码: ```javascript function listToTree(list) { const map = {}; const roots = []; // 先把每个节点的引用保存在 map 中 list.forEach(item => { map[item.id] = { ...item, children: [] }; }); // 把每个节点挂到它的父节点上 list.forEach(item => { const parent = map[item.parentId]; if (parent) { parent.children.push(map[item.id]); } else { roots.push(map[item.id]); } }); return roots; } ``` 这个函数接收一个列表作为参数,并返回一个树结构数组,其中每个节点都包含一个 `children` 属性,存放其子节点的数组。 这里的基本思路是先遍历列表,把每个节点的引用保存在 `map` 对象中。然后再遍历列表,把每个节点挂到它的父节点上,如果没有父节点则将其添加到根节点数组中。 使用示例: ```javascript const list = [ { id: 1, name: 'Node 1', parentId: null }, { id: 2, name: 'Node 1.1', parentId: 1 }, { id: 3, name: 'Node 1.2', parentId: 1 }, { id: 4, name: 'Node 1.2.1', parentId: 3 }, { id: 5, name: 'Node 2', parentId: null }, ]; const tree = listToTree(list); console.log(tree); ``` 输出: ```javascript [ { id: 1, name: 'Node 1', parentId: null, children: [ { id: 2, name: 'Node 1.1', parentId: 1, children: [], }, { id: 3, name: 'Node 1.2', parentId: 1, children: [ { id: 4, name: 'Node 1.2.1', parentId: 3, children: [], }, ], }, ], }, { id: 5, name: 'Node 2', parentId: null, children: [], }, ] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值