
interface Menus {
id?: number
parentId?: number
state?: number
children?: Menus[]
}
export function listMenusTree(list: Menus[]) {
const result = []
const itemMap: Menus = {}
for (const item of list) {
const id = item.id
const pid = item.parentId
if (!itemMap[id]) {
itemMap[id] = {
children: []
}
}
itemMap[id] = {
parentId: item.parentId,
state: item.state,
children: itemMap[id]['children']
}
const treeItem = itemMap[id]
if (pid === 0) {
result.push(treeItem)
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: []
}
}
itemMap[pid].children.push(treeItem)
}
}
return result
}
大概写法如下,业务逻辑有可能写错了,你按需调整一下: