[js]递归实现 数组转树形

let arr = [
  {pid: -1, id: 1, name: 'm1'},
  {pid: 1, id: 2, name: 'm2'},
  {pid: 2, id: 3, name: 'm3'},
  {pid: 3, id: 4, name: 'm4'},
]

数组转树方式1

const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: []
      }
      // 迭代 list, 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}

数组转树方式2

function getMenuList(authList) {
  let menu = [];
  let map = {}
  authList.forEach(m => {
    m.children = [];
    map[m.id] = m; // {1:菜单,2:菜单}
    if (m.pid === -1) {
      menu.push(m); // 如果是根 就直接push到menu中
    } else {
      map[m.pid] && map[m.pid].children.push(m);
    }
  });
  return menu
}
posted @ 2020-08-17 09:43  mmaotai  阅读(1734)  评论(0编辑  收藏  举报