现有这样一个数组
let arr = [
{
"label": "整个流程",
"value": 220,
"pid": 0,
"id": 1
},
{
"label": "群组1",
"value": 10,
"pid": 1,
"id": 2
},
{
"label": "群组2",
"value": 20,
"pid": 1,
"id": 3
},
{
"label": "群组3",
"value": 30,
"pid": 2,
"id": 4
},
{
"label": "活动1",
"value": 40,
"pid": 1,
"id": 5
},
{
"label": "活动2",
"value": 50,
"pid": 2,
"id": 6
},
{
"label": "活动3",
"value": 60,
"pid": 3,
"id": 7
}
]
需要将其转化为树结构,可用如下方法:
// 一维数组转化为树结构
const arrayToTree = (arr:any[], pid: number):any[] => {
return arr.reduce((res, current) => {
if (current['pid'] === pid) {
current.children = arrayToTree(arr, current['id'])
return res.concat(current)
}
return res
}, [])
}
arrayToTree(arr, 0)
控制台打印结果如下:
|