filterTree
过滤树形结构
过滤选项
原始树
[
{
"id": 1,
"name": "Parent 1",
"active": true,
"children": [
{
"id": 2,
"name": "Child 1-1",
"active": true
},
{
"id": 3,
"name": "Child 1-2",
"active": false
}
]
},
{
"id": 4,
"name": "Parent 2",
"active": false,
"children": [
{
"id": 5,
"name": "Child 2-1",
"active": true
}
]
}
]过滤后
[
{
"id": 1,
"name": "Parent 1",
"active": true,
"children": [
{
"id": 2,
"name": "Child 1-1",
"active": true
}
]
}
]函数签名
typescript
interface FilterTreeOptions {
childrenKey?: string
}
function filterTree<T>(
tree: T | T[],
predicate: (node: T) => boolean,
options?: FilterTreeOptions
): T[]参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
tree | T | T[] | 是 | 树形数据 |
predicate | (node: T) => boolean | 是 | 过滤条件函数 |
options | FilterTreeOptions | 否 | 配置选项 |
返回值
| 类型 | 说明 |
|---|---|
T[] | 过滤后的树形结构 |
工作原理
- 将输入转换为数组格式
- 遍历每个节点执行predicate函数
- 如果节点满足条件,保留该节点
- 递归过滤该节点的子节点
- 将过滤后的子节点挂载到节点上
- 返回过滤后的树形数组