You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
2.2 KiB

1 year ago
# 处理树结构常用算法
常用的算法大多可以在tree.js中找到,下面列举一些常用的
## transformToArrayFormat 将嵌套结构转换为id,pId解构的一维数组
```javascript
const tree = [
{
id: "root",
children: [
{
id: "1-1",
children: [
{
id: "1-1-1"
}
]
}, {
id: "1-2"
}
]
}
];
const arrayFormat = BI.Tree.transformToArrayFormat(tree);
// arrayFormat = [
// {
// "id": "root"
// },
// {
// "id": "1-1",
// "pId": "root"
// },
// {
// "id": "1-1-1",
// "pId": "1-1"
// },
// {
// "id": "1-2",
// "pId": "root"
// }
// ];
```
## transformToTreeFormat 将id,pId结构的一维数组转换为嵌套结构
```javascript
const arrayFormat = [
{
"id": "root"
},
{
"id": "1-1",
"pId": "root"
},
{
"id": "1-1-1",
"pId": "1-1"
},
{
"id": "1-2",
"pId": "root"
}
];
const tree = BI.Tree.transformToTreeFormat(arrayFormat);
// tree = [
// {
// id: "root",
// children: [
// {
// id: "1-1",
// children: [
// {
// id: "1-1-1"
// }
// ]
// }, {
// id: "1-2"
// }
// ]
// }
// ];
```
## traversal遍历树结构
`BI.Tree.traversal`方法深度优先,迭代函数传递索引,当前节点,父节点参数,迭代函数中返回`false`将终止遍历
```javascript
const tree = [
{
id: "root",
children: [
{
id: "1-1",
children: [
{
id: "1-1-1"
}
]
}, {
id: "1-2"
}
]
}
];
BI.Tree.traversal(tree, (index, item, parentNode) => {
console.log(index, item.id, parentNode ? parentNode.id : null);
});
// 0 'root' null
// 0 '1-1' 'root'
// 0 '1-1-1' '1-1'
// 1 '1-2' 'root'
```