1. 程式人生 > 實用技巧 >樹形資料結構的搜尋功能

樹形資料結構的搜尋功能

樹形結構

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
    }