1.从一个树形结构中获取一个对象的父级节点和祖先级节点
/** * 获取这个节点的父级及祖先节点 **/ function findAllParent (node, tree, parentNodes = [], index = 0) { if (!node || node.parentCode === 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.orgCode === node.parentCode) { parentNodes.push(item) return } if (item.children && item.children.length > 0) { findParent(node, parentNodes, item.children) } } }
说明 node为查找队形 tree为树