Skip to content

代码实现树结构中根据某个节点的 id 查找该节点在整棵树中完整的 id 路径,需要考虑无限级别的情况

javascript
const sourceData = [
  {
    id: '101',
    name: '101',
    children: [
      {
        id: '1001',
        name: '1001'
      },
      {
        id: '1002',
        name: '1002'
      }
    ]
  }
]

const findPathById = (data, id, path = []) => {
  for (let node of data) {
    const newPath = [...path, node.id]

    if (node.id === id) return newPath

    if (node.children) {
      const result = findPathById(node.children, id, newPath)
      if (result) return result
    }
  }
}

const nodePaths = findPathById(sourceData, '1002', [])
console.log('查询到的节点路径:', nodePaths)
javascript
const sourceData = [
  {
    id: '101',
    name: '101',
    children: [
      {
        id: '1001',
        name: '1001'
      },
      {
        id: '1002',
        name: '1002'
      }
    ]
  }
]

const buildTreeMap = (data, path = [], nodeMap = new Map()) => {
  for (let node of data) {
    const newPath = [...path, node.id]
    nodeMap.set(node.id, newPath)

    if (node.children) {
      buildTreeMap(node.children, newPath, nodeMap)
    }
  }

  return nodeMap
}

const treeMap = buildTreeMap(sourceData)
console.log('查找子节点id路径:', treeMap.get('1002'))

如何实现一个深拷贝?对于复杂数据类型如 Date、RegExp 等该如何处理?循环引用该如何处理?

js
function deepClone(obj, hash = new WeakMap()) {
  // 处理null / 非对象的情况
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  // 处理Date类型
  if (obj instanceof Date) {
    return new Date(obj)
  }

  // 处理 RegExp 类型
  if (obj instanceof RegExp) {
    return new RegExp(obj)
  }

  // 处理循环引用
  if (hash.has(obj)) {
    return hash.get(obj)
  }

  const cloneObj = Array.isArray(obj) ? [] : {}
  hash.set(obj, cloneObj)

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      cloneObj[key] = deepClone(obj[key], hash)
    }
  }

  return cloneObj
}