flit-kit
指南
API
NPM
指南
API
NPM
  • 总览
  • Tree

    • buildTree
    • traverseTree
    • findNode
    • getNodePath
    • normalizeChildren
    • pruneTreeDepth
    • getDescendants
    • getTreeDepth
    • flattenTree
    • renameTreeKeys
  • Number

    • animation

buildTree Tree

作用

将平铺列表构造成树结构,并写入层级与排序。

签名

buildTree({ list, id='id', parentId='parentId', sort='sort', childrenKey='children', comparator?, levelKey='level', emptyChildren='array', rootValue })

引入

import { buildTree } from 'flit-kit'

参数

参数类型默认值说明
listArray<object>[]平铺节点集合
idstring'id'唯一标识字段名
parentIdstring'parentId'父标识字段名
sortstring'sort'排序字段名(数值或字符串)
childrenKeystring'children'子节点字段名
comparator(a,b)=>numberundefined自定义比较函数;提供时优先于 sort
levelKeystring'level'层级字段名,根为 1
emptyChildren`'array''null''omit'`
rootValueanyundefined将 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": []
      }
    ]
  }
]
Next
traverseTree