The side-by-side structure is changed to a tree structure by association id

Encapsulate the code directly

//并排结构通过关联id变更为树结构,子id subid , 父id parentID
const treeStructure = (
  data: Array<any>,
  subid: string = "ID",
  parentID: string = "pid"
) => {
  let tableData: any = [];
  let tableDataArr = data;
  tableDataArr.map((item) => {
    //给所有对象一个children属性
    item.children = [];
    if (item[parentID] != 0) {
      tableDataArr.map((r) => {
        if (item[parentID] == r[subid]) {
          //删除子组中的children,目前只有二级分类
          delete item.children;
          r.children.push(item);
        }
      });
    }
  });
  //删除在一级外的所有子类
  tableDataArr.forEach((item) => {
    if (item[parentID] == 0) {
      tableData.push(item);
    }
  });
  return tableData;
};

When passing parameters, it is mainly the data source of the interface that is passed in, which must be an array!

Then subid is the child id, and parentID is the parent id. When parentID is 0, it means that the layer is the highest level. Specifically, a judgment is made according to the interface given by the backend.

let obj = [
    {
       name:"我是父亲"
       subid:1,
       parentID:0
    },
    {
       name:"我是儿子"
       subid:2,
       parentID:1,//parentID和subid是存在关联关系的,如果parentID和其他列的subid相同的话,那么他们肯定存在层级关系
    }
]

parentID and subid are related. If parentID is the same as the subid of other columns, then they must have a hierarchical relationship.

Through the function I wrote

can become

let obj = [
    {
       name:"我是父亲"
       subid:1,
       parentID:0,
       children:[
        {
           name:"我是儿子"
           subid:2,
           parentID:1
        }
      ]
    },
    
]

That's probably it. You can turn side-by-side data into tree-structured data, which makes it easier for us to connect to the UI library.

Guess you like

Origin blog.csdn.net/xiaoxiongxia/article/details/131580690