Skip to content

findTree ​

在树形数据中深度查找节点,支持对象、函数、值三种匹配方式,返回首个匹配项及其路径信息。

用法 ​

ts
import { findTree } from '@qingpai/utils'

// 按 id 查找(字段名可自定义)
const result = findTree(tree, 'block-1', undefined, { key: 'blockId', children: 'blocks' })

// 按条件对象查找(lodash isMatch 语义)
const result = findTree(tree, { type: 'question', attrs: { level: 2 } })

// 按函数查找
const result = findTree(tree, item => item.attrs?.['block-id'] === 'block-1')

参数 ​

名称类型描述
dataT[]树形数据数组
predicateany匹配条件:对象走 lodash isMatch、函数直接调用、其余按 id(可用 fieldNames.key 自定义,支持 'meta.id' 层级路径)比较
callback?(item, index, array, path) => boolean | void命中后的回调;显式返回 false 时终止遍历
fieldNames?{ key?: string, children?: string }自定义字段名,默认 { key: 'id', children: 'children' }

返回值 ​

FindTreeResult<T> | null — 首个匹配项及其上下文;未找到时返回 null。

ts
interface FindTreeResult<T> {
  /** 匹配到的节点 */
  item: T
  /** 节点在其所在数组中的索引 */
  index: number
  /** 节点所在的数组 */
  array: T[]
  /** 从根到该节点的路径(含自身) */
  path: T[]
}

轻排编辑器 — 教育领域富文本编辑器