const treeData=[{
id:1,parentId:null,name:"节点1",children:[{ id:11,parentId:1,name:"节点1-1" }]
},
{
id:2,parentId:null,name:"节点2",children:[{ id:22,parentId:2,name:"节点2-1" }]
}]
function getTreeData(){
let map = [];
let treeList = [];
recursion(treeData, map);
console.log(map);
TreeToList(treeData, treeList);
console.log(treeList);
}
function recursion(treeData,map){
treeData.forEach(tree=>{
map.push({id:tree.id, parentId:tree.parentId})
if(tree.children){
recursion(tree.children, map)
}
})
}
function TreeToList(treeData, listData){
treeData.forEach(tree=>{
let obj = Object.assign({},tree)
delete obj.children
listData.push(obj)
if(tree.children){
TreeToList(tree.children, listData)
}
})
}
通过当前层级的id 方向获取所有的 父层级的 label 内容
const dataTree = [
{
id: "1", label: "label1",
children: [
{id: "11", label: "label11"},
{id: "12", label: "label12",
children: [
{id: "121", label: "label121"},
{id: "122", label: "label122"},
]},
]},
{
id: "2", label: "label2",
children: [
{id: "21", label: "label21"},
{id: "22", label: "label22"},
]},
]
function handleAopLog(){
aopLog(dataTree , "121")
},
function aopLog(treeData,nodeId){
const treeList = []
const idList = []
treeToList(treeData, treeList, idList)
let levelTitle = []
levelTitle.push(getLabel(treeList,nodeId))
recursion(idList, treeList, nodeId, levelTitle)
levelTitle = levelTitle.join("》")
},
function recursion(idList, treeList, id, levelTitle){
const parentId = getId(idList, id)
if(!parentId) return
levelTitle.unshift(getLabel(treeList, parentId))
recursion( idList, treeList, parentId, levelTitle )
},
function getId(idList, id){
return idList.find(item =>item.id === id).parentId
},
function getLabel(treeList, id){
return treeList.find(tree =>tree.id === id).label
},
function treeToList(treeData, dataList, idList, parentId=null){
treeData.forEach(tree=>{
let obj = Object.assign({},tree)
delete obj.children
if(!obj.parentId) obj["parentId"] = parentId
dataList.push(obj)
idList.push({ id: obj.id, parentId: parentId })
if(!tree.children || tree.children.length===0) return
treeToList(tree.children, dataList, idList, tree.id)
})
},