以下代码可以参考:
/* * 根据ID找到所有的父级*/ function getParentNodesById(list, pid) { for (let i in list) { if (list[i].ID == pid) { return [list[i]] } if (list[i].children != null) { let node = getParentNodesById(list[i].children, pid) if (node !== undefined) { // return node.concat(list[i]) return node.POBJECT_NAME } } } } function getParentNodes(nodes, id) { const currentNode = nodes.find(node => node.ID === id); if (!currentNode || !currentNode.PID) { return []; } const parentNode = nodes.find(parentNode => parentNode.ID === currentNode.PID); if (!parentNode) { return []; } return [parentNode, ...getParentNodes(nodes, parentNode.ID)]; }