获取某个节点的所有父节点:
function getAllParentNodes(list, id) {for (let i in list) {if (list[i].id === id) {return [list[i]].filter((v) => v.id !== id);}if (list[i].children?.length > 0) {let node = getAllParentNodes(list[i].children, id);if (node) return node.concat(list[i]).filter((v) => v.id !== id);}}}
获取某个节点的兄弟节点:
function getBrotherNodes(list, id) {for (let i in list) {if (list[i].id === id) {return list.filter((v) => v.id !== id);}if (list[i].children?.length > 0) {let node = getBrotherNodes(list[i].children, id);if (node) return node.filter((v) => v.id !== id);}}}
获取某个节点的所有子节点:
function getAllChildrenNodes(list, id, arr = []) {for (let i in list) {if (list[i].id === id) {arr.push(list[i]);if (list[i].children?.length > 0) {getChild(list[i].children, arr);}} else {if (list[i].children?.length > 0) {getAllChildrenNodes(list[i].children, id, arr);}}}return arr.filter((v) => v.id !== id);}function getChild(list, arr) {list.forEach((v) => {arr.push(v);if (v.children) {getChild(v.children, arr);}});}
获取某个节点的所有父节点 id 集合:
function getParentIds(id, data) {// 深度遍历查找function dfs(data, id, parents) {for (var i = 0; i < data.length; i++) {var item = data[i];// 找到id则返回父级idif (item.id === id) return parents;// children不存在或为空则不递归if (!item.children || !item.children.length) continue;// 往下查找时将当前id入栈parents.push(item.id);if (dfs(item.children, id, parents).length) return parents;// 深度遍历查找未找到时当前id 出栈parents.pop();}// 未找到时返回空数组return [];}return dfs(data, id, []);}