UNPKG

xxm-test-js

Version:

xxm-js通用js工具(utils)库

47 lines (46 loc) 1.35 kB
/** * 查找树形数据中从根节点到目标节点的完整路径,未找到则返回空数组 * * @template T 泛型类型,表示节点对象的类型 * @param {TreeNode<T>} tree - 树形数据 * @param {T[keyof T]} target - 目标值 * @param {keyof T} [matchKey='id'] - 用于匹配的节点属性名,默认为 'id' * @param {keyof T} [childrenKey='children'] - 子节点的键名 * @returns {TreeNode<T>[]} - 从根节点到目标节点的完整路径,未找到则返回空数组 * * @example * ```typescript * // 示例使用 * interface DataItem { * id: number; * name: string; * children?: DataItem[]; * } * * const tree: DataItem = { * id: 1, * name: 'Root', * children: [ * { * id: 2, * name: 'Child 1', * children: [ * { id: 4, name: 'Grandchild 1' } * ] * }, * { * id: 3, * name: 'Child 2' * } * ] * }; * * const path = findPathInTree(tree, 4); // 未传入 matchKey,默认使用 'id' 匹配 * console.log('路径为:', path); * ``` */ export declare function findPathInTree<T extends Record<string, any>>(tree: TreeNode<T>, target: T[keyof T], matchKey?: keyof T, childrenKey?: keyof T): TreeNode<T>[]; type TreeNode<T extends Record<string, any>> = T & { children?: Array<TreeNode<T>>; }; export {};