---
title: "updateNode"
description: "Immutably update a tree node by id, rebuilding only the path from root to target while keeping untouched branches by reference."
canonical_url: "https://core.mhaibaraai.cn/en/docs/transformers/tree/update"
---
# updateNode

> Immutably update a tree node by id, rebuilding only the path from root to target while keeping untouched branches by reference.

## Usage

`updateNode` locates the node where `node[config.id] === targetId`, replaces it with the new node returned by `updater`. It only rebuilds the path from the root to the target node; untouched branches retain their original references. If the target is not found, the original tree is returned unchanged.

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

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

const next = Tree.updateNode(tree, '2', ({ node }) => ({ ...node, name: 'new' }))

// tree remains unchanged
// next[0].children[0].name === 'new'
// next[0].children[0] is a new reference; untouched sibling branches retain their original references
```

## API

`updateNode<T>(tree: TreeNode<T>[], targetId: string, updater: TreeTransformer<T, T>, config?: TreeConfig): TreeNode<T>[]`

### Parameters

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

**targetId** (`string`) *required*: The ID of the target node, matched against the key specified by config.id.

**updater** (`TreeTransformer<T, T>`) *required*: A node update function called on the matched node. Returns the replacement node.
The function receives a context object with the following properties:The matched 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

**TreeNode<T>[]**: The updated new tree array; returns the original tree if no match is found.

## Changelog

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

---

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


## Sitemap

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