选中的元素
数据结构大概:
data: [ {id:123321321, name: '哇哈哈' }, {id:123321321, name: '哇哈哈' , childrenList: [{id:888888, name: '起飞' }]}]
思路:
1、是否能在第一层找到选中的id,如果找到了,就开始递归该对象,直到找到最底层的子类
2、如果没有在第一层找到选中的id,开始递归该对象,直到找到匹配选中id的对象,而后执行第一步,找到最底层的子类
实现代码:
/*
* 第一步
* selectList 树选择控件选中的元素
*/
let categoryList = []
const findSonByRecursion = (selectList) => { // 递归树查找最底层的类目
selectList.forEach((item) => {
treeDataSource.forEach((tree) => {
if (item.value === tree.id) {
// 第一层就找到了
hasChildrenList(tree); // 开始下渗查找最底层的类目
} else {
// 否则递归继续下渗查找
if (tree.childrenList) {
findChildrenList(tree.childrenList, item.value);
}
}
});
});
};
/*
* 第二步
*/
const hasChildrenList = (tree) => { // 已经匹配上id的对象,找到该对象的最底层
if (tree.childrenList) {
tree.childrenList.forEach((item) => {
if (item.childrenList) {
hasChildrenList(item);
} else {
categoryList.push(item);
}
});
} else {
categoryList.push(tree);
}
};
/*
* 第三步
*/
const findChildrenList = (dataList, value) => {
dataList.forEach((item) => {
// childrenList 第一层就找到了
if (item.id === value) {
if (item.childrenList) {
hasChildrenList(item); // 查找是否还有子集
} else {
categoryList.push(item);
}
} else if (item.childrenList) {
// 否则继续下渗查找
findChildrenList(item.childrenList, value);
}
});
};