iView级联选择器回显问题(根据子节点id递归获取所有父类id的数组)

根据子节点递归获取所有父类id的数组

JSON数据(这里直接使用iview级联选择器里面的示例数据)

let nodes = [{
    
    
				value: 'beijing',
				label: '北京',
				children: [{
    
    
						value: 'gugong',
						label: '故宫'
					},
					{
    
    
						value: 'tiantan',
						label: '天坛'
					},
					{
    
    
						value: 'wangfujing',
						label: '王府井'
					}
				]
			}, {
    
    
				value: 'jiangsu',
				label: '江苏',
				children: [{
    
    
						value: 'nanjing',
						label: '南京',
						children: [{
    
    
							value: 'fuzimiao',
							label: '夫子庙',
						}]
					},
					{
    
    
						value: 'suzhou',
						label: '苏州',
						children: [{
    
    
								value: 'zhuozhengyuan',
								label: '拙政园',
							},
							{
    
    
								value: 'shizilin',
								label: '狮子林',
							}
						]
					}
				],
			}]

JS代码

// 根据子节点id递归获取所有父类的id
			let code = 'shizilin'   //子节点id    狮子林
			function treeFindPath (tree, func, path = []) {
    
    
			  if (!tree) return []
			  for (const data of tree) {
    
    
			    path.push(data.value)
			    if (func(data)) return path
			    if (data.children) {
    
    
			      const findChildren = treeFindPath(data.children, func, path)
			      if (findChildren.length) return findChildren
			    }
			    path.pop()
			  }
			  return []
			}
			//将递归获取到的数组赋值给result
			let result = treeFindPath(nodes, node => node.value === code)
			console.log(result,'result')

输出结果

["jiangsu","suzhou","shizilin"]    //result    江苏  苏州  狮子林

猜你喜欢

转载自blog.csdn.net/Linxi_001/article/details/121436964