写作背景
在浏览大神们的文章的时候,发现了卢哥@快跑啊小卢_的一篇关于构建高性能树的文章,感觉很受启发,文章链接我被骂了,但我学会了如何构造高性能的树状结构,其中讲述了如何快速高效的对一棵树进行增删改查,但是对于具体如何实现树和Map之间的转换没有赘述,因此我自己实现了一次。
树转Map
let tree = [
{
title: '父节点',
key: '0-0',
children: [
{
title: '子节点',
key: '0-0-0',
children: [
{
title: '孙子节点1',
key: '0-0-0-0'
},
{
title: '孙子节点2',
key: '0-0-0-1'
}
]
}
]
},
{
title: '父节点2',
key: '0-1',
children: [
{
title: '子节点',
key: '0-1-0',
children: [
{
title: '孙子节点1',
key: '0-1-0-0'
},
{
title: '孙子节点2',
key: '0-1-0-1'
}
]
}
]
}
]
// 拉平关心子节点,递归实现
const flatTree = (arr, parentId = null) => {
let flatObj = {}
arr.forEach(item => {
if (item.children) {
let childrenIds = []
item.children.forEach(child => {
childrenIds.push(child.key)
})
let obj = {
title: item.title,
parentIds: parentId || '',
childrenIds: childrenIds
}
flatObj[item.key] = obj
flatObj = { ...flatObj, ...flatTree(item.children, item.key) }
} else {
let obj = {
title: item.title,
parentIds: parentId || '',
childrenIds: []
}
flatObj[item.key] = obj
}
})
return flatObj
}
实现效果
Map转树
let objMap = {
'0-0': { 'title': '父节点', parentId: '', childrenIds: ['0-0-0'] },
'0-0-0': { 'title': '子节点', parentId: '0-0', childrenIds: ['0-0-0-0', '0-0-0-1'] },
'0-0-0-0': { 'title': '孙子节点1', parentId: '0-0-0', childrenIds: [] },
'0-0-0-1': { 'title': '孙子节点2', parentId: '0-0-0', childrenIds: [] },
}
let arr = []
// 还原只看父节点
const mapToTree = (map) => {
Object.keys(map).forEach(item => {
let obj = {
key: item,
title: map[item].title
}
if (map[item].parentId) {
addChildren(arr, map[item].parentId, obj)
} else {
arr.push(obj)
}
})
}
const addChildren = (arr, parentId, obj) => {
arr.forEach(item => {
if (item.key === parentId) {
if (item.children) {
item.children.push(obj)
} else {
item.children = [obj]
}
} else if (item.children) {
addChildren(item.children, parentId, obj)
}
})
}
mapToTree(objMap)