Skip to content

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. Like getKey, 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 ​

ArgTypeDescription
Textends objectThe type of elements of array arr
Rextends stringThe type of childrenPath

Arguments ​

ArgTypeOptionalDefaultDescription
arrT[]falseundefinedThe flat array to be converted into a tree structure
getKeystring | ((item: T, index: number, arr: T[]) => string)trueundefinedTo get the unique identifier
getParentstring | ((item: T, index: number, arr: T[]) => string)trueundefinedTo get the parent identifier
childrenPathRtrue'children'The field path in the object where child elements should be stored

Returns ​

Type
(T & DeepMappedTypeByKeyOrIndex<LiteralStringWithFallback<R, "children">, T[], false>)[]

Reference ​

LiteralStringWithFallback DeepMappedTypeByKeyOrIndex