let tree = [
{
"authId": "12",
"authType": "2",
"authName": "首页",
"authDescribe": "首页",
"authStatus": "0",
"authPid": "0",
"authUrl": "www.index.html",
"authOrder": 1,
"childAuth": [
{
"authId": "1201",
"authType": "2",
"authName": "测试",
"authDescribe": "测试",
"authStatus": "0",
"authPid": "12",
"authOrder": 0,
"childAuth":[]
}
],
"hasChild": true
}
];
console.log(tree)
let parentNode = null;
let node = null;
function getParentNode(json, nodeId,idName,childName) {
//1.第一层 root 深度遍历整个JSON
for (var i = 0; i < json.length; i++) {
if (node) {
break;
}
var obj = json[i];
//没有就下一个
if (!obj || !obj[idName]) {
continue;
}
//2.有节点就开始找,一直递归下去
if (obj.authId == nodeId) {
//找到了与nodeId匹配的节点,结束递归
node = obj;
break;
} else {
//3.如果有子节点就开始找
if (obj[childName]) {
//4.递归前,记录当前节点,作为parent 父亲
parentNode = obj;
//递归往下找
getParentNode(obj[childName], nodeId,idName,childName);
} else {
//跳出当前递归,返回上层递归
continue;
}
}
}
//5.如果木有找到父节点,置为null,因为没有父亲
if (!node) {
parentNode = null;
}
//6.返回结果obj
return {
parentNode: parentNode,
node: node
};
}
let pNode = getParentNode(tree,"1201","authId","childAuth");
console.log(pNode)