跳到主要内容

tree问题

数据结构:

js
const arr = [
{id: 1, name: '部门1', pid: 0},
{id: 2, name: '部门2', pid: 1},
{id: 3, name: '部门3', pid: 1},
{id: 4, name: '部门4', pid: 3},
{id: 5, name: '部门5', pid: 4},
]

输出结果:

js
[
{
"id": 1,
"name": "部门1",
"pid": 0,
"children": [
{
"id": 2,
"name": "部门2",
"pid": 1,
"children": []
},
{
"id": 3,
"name": "部门3",
"pid": 1,
"children": [
// 结果 ,,,
]
}
]
}
]

生成tree结构​

方式1

  • 使用Map去存储,之后遍历的同时借助对象的引用,直接从Map找对应的数据做存储

方式2:

  • 递归

递归实现​

js
/**
* 递归查找,获取children
*/
const getChildren = (data, result, pid) => {
for (const item of data) {
if (item.pid === pid) {
const newItem = {...item, children: []};
result.push(newItem);
getChildren(data, newItem.children, item.id);
}
}
}

/**
* 转换方法
*/
const arrayToTree = (data, pid) => {
const result = [];
getChildren(data, result, pid)
return result;
}

Map结构实现​

方式一:

js
function convertTree(data) {
data.forEach(function (item) {
delete item.children;// 删除 所有 children,以防止多次调用
});
// 将数据存储为 以 id 为 KEY 的 map 索引数据列
var map = {};
data.forEach(function (item) {
map[item.id] = item;
});
var val = [];
data.forEach(function (item) {
var parent = map[item.pId];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
val.push(item);
}
});
return val;
}

tree生成parentId、兄弟节点id​

js
function genTreeData(treeData,parentId){
return treeData.map((item,index)=>{
item.parentId = parentId
if(index === 0){
item.frontNodeId = ''
}else{
item.frontNodeId = treeData[index-1].key
}
if(item.children){
genTreeData(item.children,item.key)
}
})
}