这种搜索方法通常用于树形结构的数据,比如地理位置信息、组织结构、目录结构等。当你需要在这些数据中进行关键字搜索,并且需要获取包含关键字的完整路径时,这种方法就非常有用了。例如,在一个包含多层级分类的电子商务网站中,你可以使用这种方法来实现商品分类的搜索和展示,或者在一个组织结构中查找特定部门或员工的信息。总之,只要你有一个树形结构的数据,并且需要根据关键字搜索并获取完整路径,这种方法就可以派上用场。
// 定义一个名为data的对象,它包含了一些地理位置的信息
const data = {
label: '北京市',
children: [ {
label: ' 朝阳区',
children: [
{ label: ' 建外街道', },
{ label: ' 三里屯街道', }
]
},
{
label: ' 东城区',
children: [
{
label: '东直门街道',
children: [
{ label: ' 胡家园社区', },
{ label: ' 新中街社区', }
]
},
{ label: ' 东华门街道', }
]
}
]
}
// 定义一个名为search的函数,它接受一个字符串类型的参数keyWord
function search(keyWord: string) {
const result: string[] = [] // 定义一个名为result的字符串数组,用于存储搜索结果
// 定义一个名为exec的函数,它接受两个参数:data和parentPath
const exec = (data: any, parentPath: any) => {
const currentPath = parentPath.concat(data.label) // 将当前路径与父路径连接起来,形成完整的路径
// 如果当前地点的标签包含关键字
if (data.label.includes(keyWord)) {
result.push(currentPath)
}
//if (data.label.search(keyWord) > -1) {
//result.push(currentPath) // 将完整路径添加到结果数组中
//}
// 如果当前地点有子地区
if (Reflect.has(data, 'children')) {
const children = data.children // 获取子地区列表
// 遍历子地区列表
children.forEach((item: any) => {
exec(item, currentPath) // 递归调用exec函数,传入子地区和完整路径
});
}
};
exec(data, []) // 调用exec函数,传入初始地点和空路径
return result // 返回搜索结果
}
// 调用search函数,传入关键字'阳',并将结果存储在res变量中
const res = search('阳')
// 示例数据
const nationalData = [
{
label: '北京市',
children: [
{
label: '东城区',
children: [
{ label: '东华门街道' },
{ label: '王府井街道' }
]
},
{
label: '朝阳区',
children: [
{ label: '建外街道' },
{ label: '望京街道' }
]
}
]
},
{
label: '上海市',
children: [
{
label: '黄浦区',
children: [
{ label: '外滩街道' },
{ label: '豫园街道' }
]
},
{
label: '徐汇区',
children: [
{ label: '徐家汇街道' },
{ label: '漕河泾街道' }
]
}
]
}
];
//第一个参数是要搜索的数组,第二个参数是要搜索的关键字,第三个参数是可选的路径参数,用于在递归过程中传递当前的路径信息。
//在递归搜索的过程中,我们需要不断地更新当前的路径信息,以便在找到包含关键字的元素时能够获取完整的路径。因此,我们将路径作为一个参数传递给递归函数,每次递归调用时都会更新路径信息。
function searchInArray(arr, keyword, path = []) {
let result = [];
arr.forEach((item) => {
const currentPath = path.concat(item.label); // 将当前元素的标签添加到路径中
if (item.label.includes(keyword)) {
result.push(currentPath); // 如果当前元素的标签包含关键字,将完整路径添加到结果中
}
if (Array.isArray(item.children)) {
const childResults = searchInArray(item.children, keyword, currentPath); // 递归调用searchInArray,传入子数组和当前路径
result = result.concat(childResults); // 将子数组的搜索结果合并到当前结果中
}
});
return result;
}
// 调用搜索函数
const results = searchInArray(nationalData, '东');
console.log(results);