Skip to content

Latest commit

 

History

History
117 lines (103 loc) · 2.18 KB

列表转树形结构.md

File metadata and controls

117 lines (103 loc) · 2.18 KB

列表转树形结构

请实现arrayToTree函数

// 测试
const data = [
  // 注意这里,专门把pid为1的元素放一个在前面
  { id: 2, name: '部门2', pid: 1 },
  { id: 1, name: '部门1', pid: 0 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 },
  { id: 7, name: '部门7', pid: 6 },
]

console.log(JSON.stringify(arrayToTree(data), null, 2))
/*
[
  {
    "id": 1,
    "name": "部门1",
    "pid": 0,
    "children": [
      {
        "id": 2,
        "name": "部门2",
        "pid": 1,
        "children": []
      },
      {
        "id": 3,
        "name": "部门3",
        "pid": 1,
        "children": [
          {
            "id": 4,
            "name": "部门4",
            "pid": 3,
            "children": [
              {
                "id": 5,
                "name": "部门5",
                "pid": 4,
                "children": []
              }
            ]
          }
        ]
      }
    ]
  }
]
function getTreeList(rootList, id, list) {
 for(let item of rootList) {
  if(item.parent === id) {
   list.push(item)
  }
 }

 for(let i of list) {
  i.children = []
  getTreeList(rootList, i.id, list)
  if(i.children.length === 0) {
   delete i.children
  }
 }

 return list
}

const res = getTreeList(rootList, null, [])
const data = [
 // 注意这里,专门把pid为1的元素放一个在前面
 { id: 2, name: '部门2', pid: 1 },
 { id: 1, name: '部门1', pid: 0 },
 { id: 3, name: '部门3', pid: 1 },
 { id: 4, name: '部门4', pid: 3 },
 { id: 5, name: '部门5', pid: 4 },
 { id: 7, name: '部门7', pid: 6 },
]

const arrayToTree = (data) => {
 let map = new Map();
 let res = [];
 data.forEach((item) => {
   if (!item.children) {
     item.children = [];
   }
   map.set(item.id, item);
 });
 data.forEach((item) => {
   if (item.pid) {
     if (map.has(item.pid)) {
       let cur = map.get(item.pid);
       cur.children.push(item);
     }
   } else {
     res.push(item);
   }
 });
 console.log('res', res)
 return res;
};

arrayToTree(data)