父级找子集直接点就行了,子集找父级呢?怎么操作letarrn=[{"MENU_URL":"dashboard","MENU_ID":"104a580029c54e139210b7e87dca6d89","MENU_NAME":"监控面板"},{"MENU_URL":"systemManage","MENU_ID":"769130d1918d47219e6f0c463a1c9c67","MENU_NAME":"系统管理"},{"MENU_URL":"serviceManage","MENU_ID":"8619ca0b6fbc42649a27475e339d5d4a","MENU_INFO":[{"MENU_URL":"userInfo","MENU_ID":"104a580029c54e139210b7e87dca6d89","MENU_NAME":"三户信息"}],"MENU_NAME":"业务管理"},{"MENU_URL":"serviceManage/recordQuery","MENU_ID":"d379e3f38cb3472ab18287034f32ef46","MENU_INFO":[{"MENU_URL":"dashboard","MENU_ID":"104a580029c54e139210b7e87dca6d80","MENU_INFO":[{"MENU_URL":"dashboard","MENU_ID":"454a580029c54e139210b7e87dca6d82","MENU_NAME":"监控面板222"}],"MENU_NAME":"监控面板111"},{"MENU_URL":"dashboard","MENU_ID":"104a580029c54e139210b7e87dca6d89","MENU_NAME":"监控面板333"}],"MENU_NAME":"订购信息查询"}]知道监控面板222的MENU_ID,要找到最外层的MENU_ID现在写了一个能从第二级找到第一级```functiongetParentId(childId){tmparr.forEach(function(item,index){if(item.MENU_INFO){item.MENU_INFO.forEach(function(list,idx){if(list.MENU_ID===childId){console.log('d',item)}})}})}getParentId('104a580029c54e139210b7e87dca6d80')```有没有高手可以改造一下,用递归什么的,查不定级数的
2 回答
叮当猫咪
TA贡献1776条经验 获得超12个赞
有个很巧的办法:把Menu对应的数组对象arrn转成字符串,然后使用正则查找,异常轻松,可以适配无限深的层级。functionfindTopParent(menuJson,childId){letmenuStr=JSON.stringify(menuJson);letreg=newRegExp('MENU_ID":"([^"]+)"[^\\}\\]]+MENU_ID":"'+childId);returnreg.test(menuStr)?menuStr.match(reg)[1]:undefined;}findTopParent(arrn,'104a580029c54e139210b7e87dca6d89');//返回8619ca0b6fbc42649a27475e339d5d4afindTopParent(arrn,'454a580029c54e139210b7e87dca6d82');//返回d379e3f38cb3472ab18287034f32ef46
添加回答
举报
0/150
提交
取消