<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
/* 判断树形结构默认展示第一个菜单中,最里面的层级的第一个子菜单 */
function findLastLevelChildResUrl(tree,path) {
// 递归函数,用于遍历树形结构
function traverse(node,path) {
if(!node.children||node.children.length<1){
return node.resUrl
}
// 如果当前节点是数组
else if (node.children&& Array.isArray(node.children)) {
let arr = node.children;
let i = 0;
// 如果子元素是对象,则递归查找
if (!arr[i].children||arr[i].children.length<1) {
return arr[i][path]
}else{
return traverse(arr[i],path);
}
}
}
// 调用递归函数,开始遍历树形结构
return traverse(tree, path);
}
// 示例数据
let data = {
"resId": "0",
"resName": "根节点",
"moduleName": null,
"resCode": "0",
"resUrlPrefix": null,
"resUrl": null,
"children": [
{
"resId": "8a802906870da7ea0187357dbb780200",
"resName": "我的订单",
"moduleName": "我的订单",
"resCode": "ORDER_MANAGE",
"resUrl": "/orderList",
"leaf": false,
"children": [
{
"resId": "8a802906870da7ea0187357d308e01ff",
"resName": "产品订单",
"moduleName": "产品订单",
"resCode": "MY_ORDER",
"resUrlPrefix": "",
"resUrl": "/orderList1",
"leaf": true,
"disabled": false,
"children": []
},
{
"resId": "ff8080818b224628018b31e98853003c",
"resName": "产品订单2",
"moduleName": "产品订2",
"resCode": "LOAN_ORDER",
"resUrlPrefix": "",
"resUrl": "/financeOrderList",
"parentId": "8a802906870da7ea0187357dbb780200",
"leaf": true,
"disabled": false,
"children": []
}
]
}
]
}
// 使用函数查找最后一个层级的children数组下面的一个对象的resUrl值
let resUrl = findLastLevelChildResUrl(data, 'resUrl');
console.log(resUrl); // 输出找到的resUrl值,如果没有找到则输出null。
</script>
判断树形结构默认展示第一个菜单中,最里面的层级的第一个子菜单
于 2023-12-14 13:50:28 首次发布