---
title: "fromList"
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/en/docs/transformers/tree/from-list"
---
# fromList

> Convert a flat array into a nested tree using configurable id, parent id, and children fields, the core of tree-structured data.

## Usage

The `fromList` method converts a flat array with parent-child relationships (via `pid`) into a nested tree structure.

```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 will be:
[
  {
    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[]`

### Parameters

**list** (`T[]`) *required*: A flat array containing parent-child relationships.

**config** (`TreeConfig`): Configuration object for customizing the id, pid, children key names in the tree structure.Optional. The key name for the node's unique identifier. Defaults to "id".Optional. The key name for the node's parent identifier. Defaults to "pid".Optional. The key name for the children array. Defaults to "children".

### Returns

**T[]**: Returns a nested tree array.

## Changelog

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

---

- [GitHub](https://github.com/mhaibaraai/movk-core/blob/main/src/transformers/tree/convert.ts)


## Sitemap

See the full [sitemap](https://core.mhaibaraai.cn/sitemap.md) for all pages.
