# ❓ 已知数据格式,实现一个函数 fn 找出链条中所有的父级 id

const value = '112' const fn = (value) => { ... } fn(value) // 输出 [1, 11, 112]

const data = [
  {
    id: '1',
    name: 'test1',
    children: [
      {
        id: '11',
        name: 'test11',
        children: [
          {
            id: '111',
            name: 'test111',
          },
          {
            id: '112',
            name: 'test112',
          },
        ],
      },
      {
        id: '12',
        name: 'test12',
        children: [
          {
            id: '121',
            name: 'test121',
          },
          {
            id: '122',
            name: 'test122',
          },
        ],
      },
    ],
  },
]
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

# Coding

function findIdPath(id, target) {
  const match = target.find((item) => item.id === id)
  if (match) return [id]
  const _sub = target.find((item) => id.startsWith(item.id))
  return [_sub.id].concat(findIdPath(id, _sub.children))
}
1
2
3
4
5
6
// 广度优先遍历

function bfs(id, target) {
  let queue = [...target]

  while (queue.length) {
    const current = queue.shift()
    if (current.children) {
      queue.push(
        ...current.children.map((_) => ({
          ..._,
          parent: `${current.parent || current.id},${_.id}`,
        }))
      )
    }
    if (current.id === id) return (current.parent || current.id).split(',')
  }
  return []
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19