遍历递归树数组,根据子节点查询父节点中的各个层,并将这些层级合成一个数组返回,没啥可说的,直接上代码吧。
测试数据:
const treeData = [{key: '1',name: '父1',children: [{key: '11',name: '子1',children: [{key: '111',name: '孙1'},{key: '112',name: '孙2'},{key: '113',name: '孙3'},]},{key: '12',name: '子2',children: [{key: '121',name: '孙4'},{key: '122',name: '孙5'}]},]},{key: '2',name: '父2',children: [{key: '21',name: '子3',children: [{key: '211',name: '孙6'},{key: '212',name: '孙7'},{key: '213',name: '孙8'},]}]}]
js代码:
const searchParent = (map, key) => {let t = []for (let i = 0; i < map.length; i++) {const e = map[i]if (e.key === key) {//若查询到对应的节点,则直接返回t.push(e)break} else if (e.children && e.children.length !== 0) {//判断是否还有子节点,若有对子节点进行循环调用let p = searchParent(e.children, key)//若p的长度不为0,则说明子节点在该节点的children内,记录此节点,并终止循环if (p.length !== 0) {p.unshift(e)t = pbreak}}}return t}//调用函数方式searchParent(treeData,'113')