getDescendants Tree
作用
定位目标节点并返回其所有子节点列表;可选择是否包含自身。
签名
getDescendants({ tree, childrenKey='children', findKey='id', findValue, isSelf=true })
引入
import { getDescendants } from 'flit-kit'
参数
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
tree | Array<object> | [] | 输入树 |
childrenKey | string | 'children' | 子节点字段名 |
findKey | string | 'id' | 用于定位目标节点的字段名 |
findValue | any | undefined | 目标节点的字段值 |
isSelf | boolean | true | 是否将目标节点本身也包含进返回列表 |
示例
const children = getDescendants({ tree, findKey: 'id', findValue: 1 })
const withSelf = getDescendants({ tree, findKey: 'id', findValue: 1, isSelf: true })
复杂度
- O(n)
返回值
Array<object>
输出
// children
[
{ "id": 2, "parentId": 1, "name": "A-1", "sort": 1 },
{ "id": 3, "parentId": 1, "name": "A-2", "sort": 2 }
]
// withSelf
[
{ "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 }
]