2

1、数据

const 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}
];

2、数组转树

function toTree (data, pId) {
  const loop = parentId => {
    const res = []
    data.forEach(item => {
      if (item.parentId === parentId) {
        item.children = loop(item.id)
        res.push(item)
      }
    })
    return res
  }
  return loop(pId)
}

3、树转数组

function treeToArr(data) {
  const result = [];
  data.forEach(item => {
      const loop = data => {
          result.push({
            id: data.id,
            name: data.name,
            parentId: data.parentId
          });
          let child = data.children
          if(child){
            for(let i = 0; i < child.length; i++){
              loop(child[i])
            }
          }
      }
      loop(item);
  })
  return result;
}

墨城
1.7k 声望2.1k 粉丝