transform
Transform every node of a tree with a mapper function, returning a new tree whose nodes carry reshaped data and the same structure.
Usage
The transform method traverses every node in the tree and uses a transformer function to convert each node into a new shape, building a tree with a new structure.
example.ts
import { Tree } from '@movk/core'
const tree = [{ id: 1, name: 'Admin', children: [{ id: 2, name: 'Guest' }] }]
const transformedTree = Tree.transform(tree, ({ node }) => ({
key: node.id,
title: node.name,
children: [] // transformer handles child nodes
}))
/*
transformedTree will be:
[
{
key: 1,
title: 'Admin',
children: [
{ key: 2, title: 'Guest', children: [] }
]
}
]
*/
API
transform<T extends TreeNode, R extends TreeNode>(tree: T[], transformer: (context: VisitorContext<T>) => R, config?: TreeConfig): R[]
Parameters
tree
T[] required
The source tree array.
transformer
(context: VisitorContext<T>) => R required
A transformer function called for each node in the tree. Returns a new node object with the transformed structure.
The function receives a
context object with the following properties:node
T
The node currently being processed.
depth
number
The depth of the node (root node is 0).
path
T[]
An array of nodes from the root to the current node (inclusive).
index
number
The index of the current node among its siblings.
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
R[]
Returns the transformed new tree array.
Changelog
No recent changes