根据条件过滤目录树(子级匹配也要保留父级)
作者:互联网
<!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>
标签:arr,obj,name,父级,url,menu,过滤,子级,children 来源: https://www.cnblogs.com/chengyunshen/p/15898539.html