树形数据结构的搜索功能

树形结构

let tree = [{
        id: '01000000',
        text: '北京',
        children: [{
            id: '01001000',
            text: '北京市',
            children: [
                {
                    id: '01001001',
                    text: '西城区',
                    children: null,
                }, {
                    id: 12,
                    text: '东城区',
                    children: null,
                },
            ],
        }],
    }, {
        id: '02000000',
        text: '上海',
        children: [{
            id: '02001000',
            text: '上海市',
            children: [{
                id: '02001001',
                text: '黄浦区',
                children: null,
            }],
        }],
    }];

前端搜索(条件查询到的数据添加属性view=true)

function hasProp(string, prop) {
        return string.indexOf(prop) > -1;
    }

    console.log(hasProp('111', ''));
    let arr1 = [];
    filterTreeData(tree, '', arr1);
    console.log(arr1);
    for (let i = 0; i < arr1.length; i++) {
        changeTreeOpen(arr1[i], tree);
    }
    console.log(tree);

    function filterTreeData(data, val, arr1, indexArr = []) {
        data.map((item, index) => {
            let arr = [...indexArr, index];
            const children = item.children;
            item.view = false;
            item.isOpen = false;
            if (val && hasProp(item.text, val)) {
                arr1.push(arr);
            }
            if (children) {
                filterTreeData(children, val, arr1, arr);
            }
        });
    }
    // 列表树是否展开
    function changeTreeOpen(indexArr, data) {
        if (indexArr.length > 1) {
            const arr = indexArr.slice(1, indexArr.length);
            this.changeTreeOpen(arr, data[indexArr[0]].children);
            data[indexArr[0]].view = true;
        }
        data[indexArr[0]].isOpen = true;
    };

前端搜索(将查询到的数据返回,多余的数据清除掉)

//
    console.log(recursiveFn1(tree,'上'));
    function recursiveFn1(data, val) {
        let arr = []
        data.map(item => {
            if (item.children) {
                let children = item.children
                item.children = recursiveFn1(children, val)
                if (hasProp(item.text, val) || (item.children && item.children.length > 0)) {
                    arr.push(item)
                }
            } else {
                if (hasProp(item.text, val)) {
                    arr.push(item)
                }
            }
        })
        return arr
    }
原文地址:https://www.cnblogs.com/jingguorui/p/14072197.html