tanghaolin
2023-01-11 9a4868a948e46fb4e4a5bd0de82ceb008a7cd179
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
/**
 * 根据id返回树节点
 * @param id
 * @param tree
 * @returns node: Object 树节点
 */
export const findNode = (id, tree) => {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].id === id) {
      return tree[i]
    }
    if (tree[i].children && tree[i].children.length > 0) {
      const node = findNode(id, tree[i].children)
      if (node) {
        return node
      }
    }
  }
}
 
/**
 * 根据id返回所有父节点
 * @param id
 * @param tree
 * @returns *[] 父节点数组 (最近的父节点在数组末尾)
 */
export const findParents = (id, tree) => {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].id === id) {
      return [tree[i]]
    }
    if (tree[i].children && tree[i].children.length > 0) {
      const parents = findParents(id, tree[i].children)
      if (parents) {
        parents.unshift(tree[i])
        return parents
      }
    }
  }
}