• 根据条件过滤目录树(子级匹配也要保留父级)


    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title></title>
    	</head>
    	<body>
    		<script>
    			let data = [{
    				"children": [{
    					"name": "新增",
    					"url": "menu/add",
    				}, {
    
    					"children": [],
    					"name": "修改",
    					"url": "menu/modify"
    				}, {
    					"children": [],
    					"name": "删除",
    					"url": "menu/del"
    				}],
    				"name": "菜单管理",
    				"url": null
    			}, {
    				"name": "版本管理",
    				"url": null,
    				children: [{
    					name: '历史版本',
    					url: 'version/history'
    				}, {
    					name: '文件版本',
    					url: 'version/file'
    				}]
    			}]
    
    
    			const cloud = [
    				"menu/add",
    				// "menu/modify",
    				"menu/del",
    				'version/history',
    				// 'version/file'
    			]
    			console.log('===原始data====')
    			console.log(data)
    			console.log('===data====')
    
    			/**
    			 *  arr是需要转换的数组  --这里是接口返回的列表
    			 *  list 是判断条件数组  ---这里是cloud
    			 * */
    			function getNavs(arr, list) {
    				function getlist(ar) {
    					let newArr = []
    					ar.map((obj, i) => {
    						if (list.includes(obj.url)) { //当前层级url匹配
    							newArr.push(obj);
    						} else if (hasSon(obj.children)) { //子级url匹配
    							obj.children = getlist(obj.children)
    							newArr.push(obj);
    						}
    					})
    					return newArr
    				}
    				//递归子级 只需要返回true 或false  表示子级url匹配 所以当前层级也应该存在
    				function hasSon(arr) {
    					if (!arr || (arr.length == 0)) return false
    					return arr.some(item => list.includes(item.url) || hasSon(item.children))
    				}
    				return getlist(arr)
    			}
    			console.log(getNavs(data, cloud))
    		</script>
    	</body>
    </html>
    
    
  • 相关阅读:
    css中的背景、渐变 文本格式化和表格的常用属性
    HTML5中常见的英文单词
    matlab文件处理
    优先级队列
    编程珠玑(一)
    排序算法之希尔排序
    自己写的矩阵类Matrix
    排序算法之快速排序
    Thoughtworks公司面试题——MARS ROVERS问题
    matlab画图
  • 原文地址:https://www.cnblogs.com/chengyunshen/p/15898539.html
Copyright © 2020-2023  润新知