---
title: "forEach"
description: "Traverse a tree and run a visitor callback on every node, an easy way to collect, log, or mutate nodes across all depths."
canonical_url: "https://core.mhaibaraai.cn/en/docs/transformers/tree/for-each"
---
# forEach

> Traverse a tree and run a visitor callback on every node, an easy way to collect, log, or mutate nodes across all depths.

## Usage

The `forEach` method traverses every node in the tree in depth-first order and executes the `visitor` function on each node.

```ts [example.ts]
import { Tree } from '@movk/core'

const tree = [{ id: 1, name: 'A', children: [{ id: 2, name: 'B' }] }]

const names: string[] = []
Tree.forEach(tree, ({ node }) => {
  names.push(node.name)
})

// names => ['A', 'B']

// Early termination
Tree.forEach(tree, ({ node }) => {
  if (node.name === 'A') {
    return false // stop traversal
  }
})
```

## API

`forEach<T extends TreeNode>(tree: T[], visitor: (context: VisitorContext<T>) => void | false, config?: TreeConfig): void`

### Parameters

**tree** (`T[]`) *required*: The source tree array.

**predicate** (`(context: VisitorContext<T>) => boolean`) *required*: A predicate function called for each node in the tree. If the function returns true, that node and all its ancestor nodes will be retained in the result.
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".

## Changelog

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

---

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


## Sitemap

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