JS實現樹形結構數據的模糊搜索查詢


簡單示例:

需求:輸入 “題2” 字,希望樹形結構中帶有 “題2” 字的項顯示,即使父節點沒有,但子節點含有,父節點仍要返回。

let arr = [
  {
    title: '標題1',
    children: [
      {
        title: '標題11',
        children: null
      },
      {
        title: '標題21',
        children: null
      }
    ]
  },
  {
    title: '標題2',
    children: [
      {
        title: '標題22',
        children: null
      }
    ]
  },
  {
    title: '標題3',
    children: null
  }
];

代碼實現:

let mapTree = (value, arr) => {
  let newarr = [];
  arr.forEach(element => {
    if (element.title.indexOf(value) > -1) { // 判斷條件
      newarr.push(element);
    } else {
      if (element.children && element.children.length > 0) {
        let redata = mapTree(value, element.children);
        if (redata && redata.length > 0) {
          let obj = {
            ...element,
            children: redata
          };
          newarr.push(obj);
        }
      }
    }
  });
  return newarr;
};

console.log(mapTree('題2', arr));

結果:

[
  {
    title: '標題1',
    children: [
      {
        title: '標題21',
        children: null
      }
    ]
  },
  {
    title: '標題2',
    children: [
      {
        title: '標題22',
        children: null
      }
    ]
  }
]

復雜示例:

如果需要匹配多個屬性,代碼實現如下:

matchTreeData(arr, searchCon) {
  let newArr = [];
  let searchNameList = ['name', 'code', 'title'];
  arr.forEach((item) => {
    for (let i = 0, len = searchNameList.length; i < len; i++) {
      let nameKey = searchNameList[i];
      if (item.hasOwnProperty(nameKey)) {
        if (item[nameKey] && item[nameKey].indexOf(searchCon) !== -1) {
          newArr.push(item);
          break;
        } else {
          if (item.childList && item.childList.length > 0) {
            let resultArr = this.matchTreeData(item.childList, searchCon);
            if (resultArr && resultArr.length > 0) {
              newArr.push({
                ...item,
                childList: resultArr
              })
              break;
            }
          }
        }
      } else {
        continue;
      }
    }
  })
  return newArr;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM