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.

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.

Returns

T[]
Returns a nested tree array.

Changelog

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