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 => tt(v2, [...arr]))
} else {
result.push(arr)
}
}
tree.forEach(v => getPath(v, []))
return result
}
发表回复