interface TreeHelperConfig { id: string; children: string; pid: string; } const DEFAULT_CONFIG: TreeHelperConfig = { id: 'id', children: 'children', pid: 'pid', }; const getConfig = (config: Partial) => Object.assign({}, DEFAULT_CONFIG, config); export function filter(tree: T[], func: (n: T) => boolean): T[] { const children = 'children'; function listFilter(list: T[]) { return list .map((node: any) => ({ ...node })) .filter((node) => { node[children] = node[children] && listFilter(node[children]); return func(node) || (node[children] && node[children].length); }); } return listFilter(tree); } export function forEach( tree: T[], func: (n: T) => any, config: Partial = {}, ): void { config = getConfig(config); const list: any[] = [...tree]; const { children } = config; for (let i = 0; i < list.length; i++) { //func 返回true就终止遍历,避免大量节点场景下无意义循环,引起浏览器卡顿 if (func(list[i])) { return; } children && list[i][children] && list.splice(i + 1, 0, ...list[i][children]); } }