本篇文章主要介绍查询遍历树结构数据,然后得到一颗新树的方法。
1、需求如下:
要实现的效果是下图的样子,其难点主要在于对树的查询过滤后仍能得到一个保持原结构的结果树。
2、查询过滤树关键代码如下:
(1)测试数据
const tree = [
{
title: '语法',
value: '1',
key: '1',
children: [
{
title: '简单句',
value: '2',
key: '2',
children: [
{
title: '定状补',
value: '3',
key: '3',
},
{
title: '主谓宾',
value: '4',
key: '4',
},
],
},
{
title: '状态',
value: '5',
key: '5',
children: [
{
title: '一般过去时',
value: '6',
key: '6',
},
{
title: '过去时',
value: '7',
key: '7',
},
],
},
{
title: '长难句',
value: '8',
key: '8',
},
],
},
{
title: 'Node2',
value: '0-1',
key: '0-1',
children: [
{
title: 'Child Node3',
value: '0-1-0',
key: '0-1-0',
},
{
title: 'Child Node4',
value: '0-1-1',
key: '0-1-1',
},
{
title: 'Child Node5',
value: '0-1-2',
key: '0-1-2',
},
{
title: 'Child Node6',
value: '0-1-3',
key: '0-1-3',
},
],
},
{
title: 'Node3',
value: '0-3',
key: '0-3',
children: [
{
title: 'Child Node3',
value: '0-3-0',
key: '0-3-0',
},
{
title: 'Child Node4',
value: '0-3-1',
key: '0-3-1',
},
{
title: 'Child Node5',
value: '0-3-2',
key: '0-3-2',
},
],
},
{
title: 'Node4',
value: '0-4',
key: '0-4',
},
];
(2)过滤树 方法
// 过滤树并得到新树,filterArrForKey({ tree: 遍历的树, searchKey: 查询依据的key, searchValue: 查询内容 })
const filterArrForKey = ({ tree, searchKey, searchValue }) => {
if (!(tree && tree.length)) {
return [];
}
let newArr = [];
newArr = tree.map((item) => {
if (item?.[searchKey]?.toString()?.includes(searchValue)) {
return item;
}
if (item.children && item.children.length) {
const newChildren = filterArrForKey({
tree: item.children,
searchKey,
searchValue,
});
if (newChildren && newChildren.length) {
return {
...item,
children: newChildren,
};
}
return null;
}
return null;
});
newArr = newArr.filter(item => item != null);
return newArr;
};
(3)调用测试
filterArrForKey({ tree: tree, searchKey: 'title', searchValue: '过去' });