UNPKG

common-utils-y

Version:

my common utils lib

40 lines (39 loc) 1.11 kB
/** * 查找树形数据中从根节点到目标节点的完整路径,未找到则返回空数组 * @param {Array} tree - 树形数据 * @param {Function} predicate - 判断是否为目标节点的函数 * @param {String} children - 子节点数据键值, 默认值 children * @returns {Array} - 完整路径节点数组 * * @example * * const tree = [ { id: 1, name: 'Node 1', children: [ { id: 2, name: 'Node 1.1', children: [ { id: 3, name: 'Node 1.1.1', children: [] }, { id: 4, name: 'Node 1.1.2', children: [] }, ], }, { id: 5, name: 'Node 1.2', children: [] }, ], }, { id: 6, name: 'Node 2', children: [ { id: 7, name: 'Node 2.1', children: [] }, { id: 8, name: 'Node 2.2', children: [] }, ], }, ]; const path = findPathInTree(tree, (node) => node.id === 4); console.log(path.map((node) => node.name).join(' -> ')); // 输出: Node 1 -> Node 1.1 -> Node 1.1.2 */ export declare function findPathInTree<T>(treeData: T[], predicate: (node: T) => boolean, children?: string): T[];