JS获取一颗树的一个节点

JS获取一颗树的一个节点

徐徐
前端
发布于2024-08-20 16:15:07
🌺前言
JS获取一颗树的一个节点

javascript
/**
 * 查询一个树的子节点
 * @param {object} nodes
 * @param {string} target 目标节点id
 * @param {object} props
 * @returns
 */
export default function useDeepFindTreeNode (
  nodes,
  target,
  props = { id: 'id', children: 'children' }
) {
  let result = null
  function findNode (arr, tag, props) {
    if (!arr || !arr.length) {
      return
    }
    for (let i = 0; i < arr.length; i++) {
      if (arr[i][props.id] === tag) {
        result = arr[i]
        break
      } else if (arr[i][props.children] && arr[i][props.children].length) {
        findNode(arr[i][props.children], tag, props)
      }
    }
  }

  findNode(nodes, target, props)
  return result
}
文章最后更新于 2024-08-20 16:15:07
留言
暂无数据

~~空空如也