首页 新闻 会员 周边 捐助

查找子节点的所有父节点

0
悬赏园豆:30 [已解决问题] 解决于 2021-04-20 10:21
 var routes = [ { title: '首页', key: '/app/dashboard', icon: 'HomeOutlined', isPublic: true, isMenu: 1, id: 1, pid: 0 }, { title: '商品', key: '/app/products', icon: 'ClusterOutlined', isMenu: 1, id: 2, pid: 0, children: [ { title: '品类管理', key: '/app/category', icon: 'GoldOutlined', isMenu: 1, id: 3, pid: 2 }, { title: '商品管理', key: '/app/product', icon: 'AppstoreOutlined', isMenu: 1, id: 4, pid: 2 } ] }, { title: '图形图表', key: '/app/charts', icon: 'AreaChartOutlined', isMenu: 1, id: 7, pid: 0, children: [ { title: '柱形图', key: '/app/charts/bar', icon: 'BarChartOutlined', isMenu: 1, id: 8, pid: 7 }, { title: '折线图', key: '/app/charts/line', icon: 'LineChartOutlined', isMenu: 1, id: 9, pid: 7 }, { title: '饼图', key: '/app/charts/pie', icon: 'PieChartOutlined', isMenu: 1, id: 10, pid: 7 } ] }, { title: '状态管理', key: '/app/store', icon: 'ApartmentOutlined', isMenu: 1, id: 11, pid: 0 } ]; 

上面是数据,我有一个pathname/app/charts/pie,改方法需要返回:

let result = { title: '图形图表', key: '/app/charts', icon: 'AreaChartOutlined', isMenu: 1, id: 7, pid: 0, children: [ { title: '折线图', key: '/app/charts/line', icon: 'LineChartOutlined', isMenu: 1, id: 9, pid: 7 } ] } 

求该方法

U型枕的主页 U型枕 | 菜鸟二级 | 园豆:231
提问于:2021-04-19 16:44
< >
分享
最佳答案
0
/** * 获取指定元素的所有父级对象的索引 * @param {array} treeData - 要匹配的树 * @param {string} $selectKey - 要匹配的元素 * github: https://github.com/chenyin151/GetParentForTree */ export const getParentForTree = (treeData, $selectKey) => { for (let i = 0; i < treeData.length; i++) { const layer = 0; const posIndx = []; const item = treeData[i]; if (item.key === $selectKey) { return [{ key: item.key, title: item.title }]; } else { const res = scanTree(item, $selectKey, layer, posIndx); if (res) return res; } } }; /** * 扫描树下面的孩子对象 * @param {object} $item - 要递归遍历的对象 * @param {string} $key - 要匹配的元素 * @param {number} $layer - 遍历到哪一级孩子对象 * @param {array} $posIndx - 用来存储匹配到的元素的所有父级 * @returns {array} - 匹配到的元素的所有父级 */ const scanTree = ($item, $key, $layer, $posIndx) => { // console.log('layer', $item, $key, $layer, $posIndx); if (!$item.children) { $layer -= 1; return false; } $posIndx[$layer] = { key: $item.key, title: $item.title }; for (let i = 0; i < $item.children.length; i++) { const item = $item.children[i]; if (item.key === $key) { // console.log('找到节点,节点位置是:', i); $posIndx.push({ key: item.key, title: item.title }); return $posIndx; } else { // console.log('深入到子节点'); const layer = $layer + 1; const node = scanTree(item, $key, layer, $posIndx); if (!node && $posIndx.length > 0) { $posIndx.length -= 1; $posIndx[$layer] = { key: $item.key, title: $item.title }; } if (node) return node; } } }; 
U型枕 | 菜鸟二级 |园豆:231 | 2021-04-20 10:20
其他回答(1)
0

这个你不是都知道 地址是/app/charts/pie了么,那找到key ='/app/charts/pie'的值,然后这个值有对应的pid,再根据pid找父级不就出来了吗?

收获园豆:30
Mr丶Yan | 园豆:5 (初学一级) | 2021-04-20 10:17
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册