五维思考

学习要加,骄傲要减,机会要乘,懒惰要除。 http://www.5dthink.cn

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

源数组

树形菜单

方法一

import {menus} from './menus.ts'

function listToTree(list: any = [], options = {}, data = null) {
  const { rootWhere, childsWhere, addChilds } = Object.assign(
    { 
      rootWhere: (parent:any,self: any) => {
        return self.parentId === 0
      },
      childsWhere: (parent: any, self: any) => {
        return parent.id === self.parentId
      },
      addChilds: (parent: any, childList: any) => {
        if (childList?.length > 0) {
          parent['children'] = childList
        }
      }
    },
    options || {}
  )
  let tree = [] as any
  // 空列表
  if (!(list?.length > 0)) {
    return tree
  }
  // 顶级
  const rootList = list.filter((item: any) => rootWhere && rootWhere(data, item))
  if (!(rootList?.length > 0)) {
    return tree
  }
  tree = tree.concat(rootList)
  // 子级
  tree.forEach((root: any) => {
    const rootChildList = list.filter((item: any) => childsWhere && childsWhere(root, item))
    if (!(rootChildList?.length > 0)) {
      return
    }
    rootChildList.forEach((item: any) => {
      const childList = listToTree(list, { rootWhere: childsWhere, childsWhere, addChilds }, item)
      addChilds && addChilds(item, childList)
    })
    addChilds && addChilds(root, rootChildList)
  })

  return tree
}

const menuTree = listToTree(menus) // menuTree为最终想要的树形菜单数组

方法二

import {menus} from './menus.ts'

interface menuType {
    id: string | number,
    parentId: string | number,
    children?: menuType[]
    [key: string]: any
}

// datas:后端传过来的菜单数组
// list:当前层级列表
const toTree = (datas: menuType[], list: menuType[]) => {
  list.forEach((item: menuType) => {
    const tmpMenu = { ...item }
    const children = datas.filter((u: menuType) => u.parentId === tmpMenu.id)
    if (children && children.length > 0) {
      item.children = item.children || []
      item.children.push(...children)
      toTree(datas, children)
    }
  })
}
const menuTree = menus.filter(x => x.parentId === 0)
toTree(menus, menuTree) // 调用函数,向menuTree添加children,menuTree为最终想要的树形菜单数组

【注】需要 vue + element 渲染树形菜单的
请参考:https://blog.csdn.net/weixin_38422287/article/details/113999664

posted on 2023-01-24 22:05  五维思考  阅读(564)  评论(0编辑  收藏  举报

QQ群:1. 全栈码农【346906288】2. VBA/VSTO【2660245】