递归-树结构和数组对象之间的相互转换

1、将树结构展平成数组对象

// 获取平铺结构
  const tile = (data: any) => {
    let arr: any = [];
    for (let i = 0, l = data.length; i < l; i++) {
      arr.push(data[i]);
      if (data[i].childMenuList && data[i].childMenuList.length > 0) {
        arr = arr.concat(tile(data[i].childMenuList));
      }
    }
    return arr;
  };

 

2、将数组对象生成树结构

// 根据平铺结构生成树结构
  const genTreeData = (originData: any) => {
    const rootNode = originData.filter((n: any) => n.parId === 0);
    const genChildren = (parents: any) => {
      const tempParents = parents.map((parent: any) => {
        const children = originData.filter((m: any) => m.parId === parent.id);
        const tempParent = {
          ...parent,
          key: parent.id,
          title: parent.menuName,
        };
        if (children.length > 0) {
          tempParent.children = genChildren(children);
        }
        return tempParent;
      });
      return tempParents;
    };
    const tempTreeData = genChildren(rootNode);
    return tempTreeData;
  };

 

posted @ 2021-04-11 17:38  吴小明-  阅读(486)  评论(0编辑  收藏  举报