js扁平一维数组转换成树结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let data = [
{
"funcId": 1,
"funcName": "菜单管理",
"funcType": 1,
"funcIcon": "el-icon-close",
"parentId": 0,
"url": "/menu",
"path": "menu",
},
{
"funcId": 2,
"funcName": "菜单管理1",
"funcType": null,
"funcIcon": "el-icon-close",
"parentId": 1,
"url": "/menu",
"path": "menu",
},
{
"funcId": 3,
"funcName": "菜单管理2",
"funcType": 2,
"funcIcon": "el-icon-close",
"parentId": 2,
"url": "/menu",
"path": "menu",
},
{
"funcId": 4,
"funcName": "菜单管理3",
"funcType": 2,
"funcIcon": "el-icon-close",
"parentId": 3,
"url": "/menu",
"path": "menu",
}
]
function tree(data,arr=[]) {
data.forEach(item=> {
if(item.parentId==0) {
arr.push({...item,children:[]})
}else {
getItem(item,arr)
}
})
return arr
}
function getItem(data,arr) {
arr.forEach(v=> {
if(v.funcId==data.parentId) {
if(!v.children) {
v.children = [data]
}else {
v.children.push(data)
}
}else {
if(v.children) {
getItem(data,v.children)
}else {
return
}
}
})
}
let res = tree(data,[])
console.log(res,'aa')
</script>
</body>
</html>