fromList

将一个扁平的、包含父子关系(通过 pid)的数组转换为树形结构。

fromList

fromList 方法将一个扁平的、包含父子关系(通过 pid)的数组转换为树形结构。

用法

import { Tree } from '@movk/core'

const list = [
  { id: 1, pid: 0, name: 'root' },
  { id: 2, pid: 1, name: 'child 1' },
  { id: 3, pid: 1, name: 'child 2' },
  { id: 4, pid: 2, name: 'grandchild' }
]

const tree = Tree.fromList(list)

/*
tree 将会是:
[
  {
    id: 1,
    pid: 0,
    name: 'root',
    children: [
      {
        id: 2,
        pid: 1,
        name: 'child 1',
        children: [
          { id: 4, pid: 2, name: 'grandchild', children: [] }
        ]
      },
      { id: 3, pid: 1, name: 'child 2', children: [] }
    ]
  }
]
*/

API

fromList<T extends TreeNode>(list: T[], config?: TreeConfig): T[]

参数

list
T[] required
包含父子关系的扁平数组。
config
TreeConfig
用于自定义树形结构中 id, pid, children 键名的配置对象。

返回值

T[]
返回一个树形结构的节点数组。

Changelog

No recent changes
Copyright © 2024 - 2025 YiXuan - MIT License