正常来说element框架应该返回的,但实际上没有,只能自己处理了
递归处理,思路就是赋值,如果是自己过滤到的数据就push进去,不是就不要
let newCheckTree = []
let tree = get_tree(treeData,newCheckTree); //获取过滤后的数据
function get_tree(treeData,newCheckTree,expandedList){for(var i = 0;i< treeData.length;i++){if(treeData[i].child.length){newCheckTree[i] = {...treeData[i]} //把所有的值赋上,但是child要为空,不然就一模一样了newCheckTree[i].child = []newCheckTree[i].child = findChildren(treeData[i].child,newCheckTree[i].child) }else{let val = treeData[i].jGMC.toUpperCase()if(val.indexOf(filterText) !== -1){newCheckTree.push(treeData[i])// console.log(expandedList,'that.expandedList')if(expandedList.indexOf(treeData[i].sid) == -1){expandedList.push(treeData[i].sid)}}}}return newCheckTree}function findChildren(treeData,newCheckTree){for(var i = 0;i< treeData.length;i++){if(treeData[i].child.length){newCheckTree[i] = {...treeData[i]}newCheckTree[i].child = []newCheckTree[i].child = findChildren(treeData[i].child,newCheckTree[i].child) }let val = treeData[i].jGMC.toUpperCase()if(val.indexOf(filterText) !== -1){newCheckTree.push(treeData[i])// console.log(expandedList,'that.expandedList')if(expandedList.indexOf(treeData[i].sid) == -1){expandedList.push(treeData[i].sid)}}}return newCheckTree}
优化
其实这样拿到的数据虽然是过滤后的,但是也包括了父元素
比如一个父元素有七个子元素,这七个子元素都不是我们过滤到的,所以这时候应该连父元素一起都不要的
但是这个操作在递归里不好实现
所以还要再来一次处理
let newCheckTree = get_tree1(JSON.parse(JSON.stringify(tree))); //删掉过滤后没有子元素的数据,深拷贝不然会被影响
function get_tree1(treeData){for(var i = 0;i< treeData.length;i++){if(treeData[i]){if(treeData[i].child.length){treeData[i].child = findChildren1(treeData[i].child) }else{//如果没有子数据就删掉它treeData.splice(i,1)i--}}}return treeData}function findChildren1(treeData){for(var i = 0;i< treeData.length;i++){// console.log(treeData,'treeData')if(treeData[i]){if(treeData[i].child.length){}else{treeData.splice(i,1)i--}}}return treeData}