buildTree Tree
作用
将平铺列表构造成树结构,并写入层级与排序。
签名
buildTree({ list, id='id', parentId='parentId', sort='sort', childrenKey='children', comparator?, levelKey='level', emptyChildren='array', rootValue })
引入
import { buildTree } from 'flit-kit'
参数
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
list | Array<object> | [] | 平铺节点集合 |
id | string | 'id' | 唯一标识字段名 |
parentId | string | 'parentId' | 父标识字段名 |
sort | string | 'sort' | 排序字段名(数值或字符串) |
childrenKey | string | 'children' | 子节点字段名 |
comparator | (a,b)=>number | undefined | 自定义比较函数;提供时优先于 sort |
levelKey | string | 'level' | 层级字段名,根为 1 |
emptyChildren | `'array' | 'null' | 'omit'` |
rootValue | any | undefined | 将 parentId===rootValue 视为根 |
示例
const nodes = [
{ id: 1, parentId: null, name: 'A', sort: 2 },
{ id: 2, parentId: 1, name: 'A-1', sort: 1 },
{ id: 3, parentId: 1, name: 'A-2', sort: 2 },
]
const tree = buildTree({ list: nodes, sort: 'sort', levelKey: 'level', emptyChildren: 'array' })
复杂度与行为
- 组装 O(n);兄弟排序近似 O(n log n)
- 不修改输入
list,输出新对象结构
返回值
Array<object>树的根节点数组
输出
[
{
"id": 1,
"parentId": null,
"name": "A",
"sort": 2,
"level": 1,
"children": [
{
"id": 2,
"parentId": 1,
"name": "A-1",
"sort": 1,
"level": 2,
"children": []
},
{
"id": 3,
"parentId": 1,
"name": "A-2",
"sort": 2,
"level": 2,
"children": []
}
]
}
]