---
title: "insertBefore"
description: "Insert a new node immediately before a target node in a tree by id, returning whether the insertion succeeded."
canonical_url: "https://core.mhaibaraai.cn/en/docs/transformers/tree/insert-before"
---
# insertBefore

> Insert a new node immediately before a target node in a tree by id, returning whether the insertion succeeded.

## Usage

The `insertBefore` method inserts a new node immediately before the target node (found by `id`). This method **mutates** the tree array in place.

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

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

Tree.insertBefore(tree, newNode, 2)

/*
tree will be:
[{ id: 1, name: 'A' }, { id: 3, name: 'B' }, { id: 2, name: 'C' }]
*/
```

## API

`insertBefore<T extends TreeNode>(tree: T[], node: T, targetId: number | string, config?: TreeConfig): boolean`

### Parameters

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

**node** (`T`) *required*: The new node to insert.

**targetId** (`number | string`) *required*: The ID of the target node. The new node will be inserted before this node.

**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

**boolean**: Returns true if the target was found and the new node was successfully inserted, otherwise false.

## Changelog

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

---

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


## Sitemap

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