arr = [
["a", "aa", "aaa", "aaaa"],
["b", "bb", "bbb"],
["a", "ab", "aba"],
["a", "aa", "aab"]
]tree = [
{
"name":"a",
"child":[
{
"name":"aa",
"child":[
{
"name":"aaa",
"child":[
{
"name":"aaaa",
"child":[]
}
]
},
{
"name":"aab",
"child":[]
}
]
},
{
"name":"ab",
"child":[
{
"name":"aba",
"child":[]
}
]
}
]
},
{
"name":"b",
"child":[
{
"name":"bb",
"child":[
{
"name":"bbb",
"child":[]
}
]
}
]
}
] 1. 数组转换为树形结构 要点:节点的存储与引用 function ArrToTree(arr) {
let result =[] // 结果
let concatStr = "=====" // 连接符(随便写,保证key唯一性就OK)
let map = new Map() // 存储根节点
function addList(list) {
let path = [] // 路径
let node // 当前节点
list.forEach(v => {
path.push(v)
let key = path.join(concatStr)
let item = { name: v, child: [] } // 当前节点
if(map.has(key)) {
item = map.get(key)
} else {
map.set(key, item) // 存储路径对应的节点
if(node) {
node.child = (node.child || []).concat(item)
} else {
result.push(item)
}
}
node = item // 更新当前节点
})
}
arr.forEach(v => addList(v))
return result
}2. 树形结构转换为数组 function TreeToArr(tree) {
let result = [] // 结果
function getPath(node, arr) {
arr.push(node.name)
if(node.child.length > 0) { // 存在多个节点就递归
node.child.forEach(v2 => getPath(v2, [...arr]))
} else {
result.push(arr)
}
}
tree.forEach(v => getPath(v, []))
return result
}
|