zhengyiming
2025-02-10 958b79ed89b9e742540f714a80261d222c0fc09b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export function getTree(
  data: API.ModuleDto[],
  root?: string,
  idTxt = 'id',
  pidTxt = 'parentId',
  pushTxt = 'children'
) {
  // 递归方法
  function getNode(id: string | undefined) {
    const node = [];
    for (let i = 0; i < data.length; i++) {
      if (data[i][pidTxt] === id) {
        data[i][pushTxt] = getNode(data[i][idTxt]);
        node.push(data[i] as never);
      }
    }
    if (node.length === 0) {
      return;
    } else {
      return node;
    }
  }
  // 使用根节点
  return getNode(root);
}
 
type FlattenTreeOptions = {
  childrenKey?: string;
};
 
export function flattenTree<T = any>(tree: T[], options: FlattenTreeOptions = {}) {
  const { childrenKey = 'children' } = options;
 
  const result: T[] = [];
 
  function traverse(node: T) {
    result.push(node);
    if (node[childrenKey] && node[childrenKey].length > 0) {
      node[childrenKey].forEach((child) => traverse(child));
    }
  }
 
  tree.forEach((node) => traverse(node));
 
  return result;
}