主体函数
export function findAllParent (node, tree, parentNodes = [], index = 0) { if (!node || node.fid === 0) { return } findParent(node, parentNodes, tree) let parentNode = parentNodes[index] findAllParent(parentNode, tree, parentNodes, ++index) return parentNodes } function findParent (node, parentNodes, tree) { for (let i = 0; i < tree.length; i++) { let item = tree[i] if (item.id === node.fid) { parentNodes.push(item) return } if (item.children && item.children.length > 0) { findParent(node, parentNodes, item.children) } } } export default findAllParent
调用方式
import findParentNodes from './test' let menuTreeData = [ { id: 1, fid: 0, name: '1', children: [ { id: 11, fid: 1, name: '1-1', children: [ { id: 111, fid: 11, name: '1-1-1' }, { id: 112, fid: 11, name: '1-1-2' } ] }, { id: 12, fid: 1, name: '1-2' } ] }, { id: 2, fid: 0, name: '2' } ] let nodes = [] let parentNodes = findParentNodes({ id: 112, fid: 11 }, menuTreeData, nodes) console.error('tag', nodes.map(item => item.name)) console.error('tag', parentNodes.map(item => item.name))
两种方式都可以获取到祖先节点的值