首页 > 其他 > 详细

树形数据结构的搜索功能

时间:2020-12-02 10:52:14      阅读:85      评论:0      收藏:0      [点我收藏+]

树形结构

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!