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.id
string
Optional. The key name for the node's unique identifier. Defaults to "id".
pid
string
Optional. The key name for the node's parent identifier. Defaults to "pid".
children
string
Optional. The key name for the children array. Defaults to "children".
Returns
T[]
Returns a nested tree array.
Changelog
No recent changes