扁平数组与树数组间的转换

50 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let arr = [
        { id: 2, name: "部门B", parentId: 0 },
        { id: 3, name: "部门C", parentId: 1 },
        { id: 1, name: "部门A", parentId: 2 },
        { id: 4, name: "部门D", parentId: 1 },
        { id: 5, name: "部门E", parentId: 2 },
        { id: 6, name: "部门F", parentId: 3 },
        { id: 7, name: "部门G", parentId: 2 },
        { id: 8, name: "部门H", parentId: 4 },
      ];
      
      const arrToTree = function (arr, pid = 0) {
        return arr.reduce((res, cur) => {
          if (cur.parentId === pid) {
            //递归寻找
            const children = arrToTree(arr, cur.id);
            if (children.length) {
              cur.children = children;
            }
            res.push(cur);
          }
          return res;
        }, []);
      };
      const tree = arrToTree(arr)
      console.log(tree,'tree');

      const treeToArr = function(tree){
        return tree.reduce((res,cur)=>{
            //没有子
            if(!cur.children){
                res.push(cur)
            }else{
                //有就递归+删除.children关系
                const childrenList = treeToArr(cur.children)//递归
                delete cur.children//删除关系
                res.push(cur,...childrenList)//把子数组展开添加
            }
            return res//记得返回每次的结果
        },[])
      }
      const array = treeToArr(tree) 
      console.log(array,'array');
    </script>
  </body>
</html>