一 说明
项目需要对树形结构进行模糊搜索,就在网上找了本篇文章。为了保留着,抄写了一份作为记录。 本篇文章原文为:JS实现树形结构数据的模糊搜索查询
1. 需求:
输入 “题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
}
]
}
]
2. 过滤多个属性,代码实现如下:
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;
}