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:
config
TreeConfig
Configuration object for customizing the id, pid, children key names in the tree structure.

Returns

R[]
Returns the transformed new tree array.

Changelog

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