[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
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM