---
title: "transform"
description: "Transform every node of a tree with a mapper function, returning a new tree whose nodes carry reshaped data and the same structure."
canonical_url: "https://core.mhaibaraai.cn/en/docs/transformers/tree/transform"
---
# 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.

```ts [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:The node currently being processed.The depth of the node (root node is 0).An array of nodes from the root to the current node (inclusive).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.Optional. The key name for the node's unique identifier. Defaults to "id".Optional. The key name for the node's parent identifier. Defaults to "pid".Optional. The key name for the children array. Defaults to "children".

### Returns

**R[]**: Returns the transformed new tree array.

## Changelog

See commit history for [src/transformers/tree/transform.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/transformers/tree/transform.ts).

---

- [GitHub](https://github.com/mhaibaraai/movk-core/blob/main/src/transformers/tree/transform.ts)


## Sitemap

See the full [sitemap](https://core.mhaibaraai.cn/sitemap.md) for all pages.
