---
title: "findById"
description: "通过节点 id 在树形结构中快速查找并返回匹配节点，未找到时返回 undefined。"
seo_title: "findById"
seo_description: "Find a single tree node by its id using the configured id field, returning the node or undefined when no match exists."
canonical_url: "https://core.mhaibaraai.cn/docs/transformers/tree/find-by-id"
---
# findById

> 通过节点 id 在树形结构中快速查找并返回匹配节点，未找到时返回 undefined。

## 用法

`findById` 方法通过节点的 `id` 快速查找并返回对应的节点。这是一个高效率的查找操作。

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

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

const node = Tree.findById(tree, 2)

// node => { id: 2, name: 'B' }
```

## API

`findById<T extends TreeNode>(tree: T[], id: number | string, config?: TreeConfig): T | undefined`

### 参数

**tree** (`T[]`) *required*: 源树形结构数组。

**id** (`number | string`) *required*: 需要查找的节点的 ID。

**config** (`TreeConfig`): 用于自定义树形结构中 id, pid, children 键名的配置对象。可选。指定节点唯一标识符的键名。默认为 "id"。可选。指定节点父级标识符的键名。默认为 "pid"。可选。指定子节点数组的键名。默认为 "children"。

### 返回值

**T | undefined**: 返回找到的节点，如果未找到则返回 undefined。

## Changelog

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


## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
