最新通知
递归树形节点搜索过滤
阅读次数:733 最后编辑时间:1970年01月01日

概述

根据关键字查询树型数据相关节点。

// 查找节点的父元素
function findParent(data, id) {
    // 返回数据集合
    var result = [];
    // 声明digui函数
    var fnc = function(arr, id) {
        // 遍历树
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if (item[props.nodeKey] == id) {
                 // 查找到指定节点加入集合
                result.push(item);
                // 查找其父节点
                fnc(data, item.parentId);
                    // 不必向下遍历,跳出循环
                    break;
            } else {
                if (item[props.props.children]) {
                     // 向下查找到id
                     fnc(item[props.props.children], id);
                }
            }
        }
    };
    // 调用函数
    fnc(data, id);
    // 返回结果
    return result;
};

// 模糊查询
function filter(nodes, query) {
    // 条件就是节点的title过滤关键字
    let newChildren = [];
    let findParentList = []
    let fnc = function (nodes, query) {
        nodes.forEach(item => {
            if (item.label.indexOf(query) > -1) {
                newChildren.push(item);
            }
            if (item.children) {
                fnc(item.children, query)
            }
        })
    }
    // 调用
    forFn(nodes, query)
    // 调用递归查询父id
    newChildren.forEach(item => {
        findParentList.push(findParent(dataTree,item.id))
    })

    if (findParentList&&findParentList.length) {
        let flat= findParentList.reduce(function(prev,next){
            return prev.concat(next);//循环将数组进行拼接
        });
        // 去重
        let newList = new Set(flat)
        return newList?Array.from(newList): [];
    } else {
        return []
    }
};