linkToTree
Converts a flat array arr
into a tree structure and returns the array of root nodes.
This is useful for build the tree options from flat array.
Note: this function can modify the elements of arr
.
Optional parameters:
getKey
: Used to obtain the unique identifier for each element. This can be a field path for getByPath or a function.getParent
: Retrieves the parent identifier for each element. LikegetKey
, it can be a field path for getByPath or a function.childrenPath
: Specifies the field path in the object where child elements should be stored. It defaults to'children'
. Both getByPath and setByPath will utilize this path when accessing or modifying the child elements.
Added in v0.0.2
Usage
ts
import { linkToTree } from 'parsnip-kit'
const arr = [
{ id: '1', parentId: null, name: 'Root 1' },
{ id: '2', parentId: '1', name: 'Child 1' },
{ id: '3', parentId: '1', name: 'Child 2' },
{ id: '4', parentId: '2', name: 'Grandchild 1' },
{ id: '5', parentId: null, name: 'Root 2' }
]
const result = linkToTree(arr, 'id', 'parentId', 'items')
// [
// {
// id: '1',
// parentId: null,
// name: 'Root 1',
// items: [
// {
// id: '2',
// parentId: '1',
// name: 'Child 1',
// items: [
// {
// id: '4',
// parentId: '2',
// name: 'Grandchild 1',
// items: []
// }
// ]
// },
// {
// id: '3',
// parentId: '1',
// name: 'Child 2',
// items: []
// }
// ]
// },
// {
// id: '5',
// parentId: null,
// name: 'Root 2',
// items: []
// }
// ]
API
Type Parameter
Arg | Type | Description |
---|---|---|
T | extends object | The type of elements of array arr |
R | extends string | The type of childrenPath |
Arguments
Arg | Type | Optional | Default | Description |
---|---|---|---|---|
arr | T[] | false | undefined | The flat array to be converted into a tree structure |
getKey | string | ((item: T, index: number, arr: T[]) => string) | true | undefined | To get the unique identifier |
getParent | string | ((item: T, index: number, arr: T[]) => string) | true | undefined | To get the parent identifier |
childrenPath | R | true | 'children' | The field path in the object where child elements should be stored |
Returns
Type |
---|
(T & DeepMappedTypeByKeyOrIndex<LiteralStringWithFallback<R, "children">, T[], false>)[] |