Js通过value查找树型数据所有的父节点

2023-07-24 17:32:05 浏览数 (1)

代码语言:javascript复制
 const tree = [{
    value: 1, label: "1",
    children: [{
      value: 11, label: "1-1",
      children: [{
        value: 111, label: "1-1-1"
      }]
    }]
  }, {
    value: 2, label: "2"
  }]

  function findNodeByValue(tree, value) {
    for (let node of tree) {
      if (node.value === value) {
        return [node]
      }
      if (node.children) {
        const result = findNodeByValue(node.children, value)
        if (result) {
          return [node, ...result]
        }
      }
    }
    return null
  }

  const result = findNodeByValue(tree, 111)

0 人点赞