---
title: "fromList"
description: "将一个扁平的、包含父子关系（通过 `pid`）的数组转换为树形结构。"
seo_title: "fromList"
seo_description: "Convert a flat array into a nested tree using configurable id, parent id, and children fields, the core of tree-structured data."
canonical_url: "https://core.mhaibaraai.cn/docs/transformers/tree/from-list"
---
# fromList

> 将一个扁平的、包含父子关系（通过 \`pid\`）的数组转换为树形结构。

## 用法

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

```ts [example.ts]
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 键名的配置对象。可选。指定节点唯一标识符的键名。默认为 "id"。可选。指定节点父级标识符的键名。默认为 "pid"。可选。指定子节点数组的键名。默认为 "children"。

### 返回值

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

## Changelog

See commit history for [src/transformers/tree/convert.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/transformers/tree/convert.ts).


## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
