UNPKG

wg-little-tools

Version:

常用工具类

125 lines (119 loc) 3 kB
export class Tree { /** * @description 创建树形结构 * @param {*} data */ createTree(data) { const tree = []; const teeeMap = new Map(data.map(item => [item.id, item])); data.forEach(item => { if (!item.parentId) { tree.push(item); } else { const parent = teeeMap.get(item.parentId); if (parent) { parent.children = parent.children || []; parent.children.push(item); } } }); return tree; } /** * @description 把树形结构flat * @param {*} treeData * @returns */ flatTree(treeData) { const result = []; treeData.forEach(node => { const newNode = { ...node }; delete newNode.children; // 删除children属性 result.push(newNode); if (node.children) { result.push(...flatTree(node.children)); } }); return result; } /** * @description 获取树形结构中某一节点的所有祖先节点 * @param {*} treeData * @param {*} id */ getAncestors(treeData, id) { // 祖先节点容器 const ancestors = []; function findAncestors(node, path = []) { if (node.id === id) { ancestors.push(...path); return true; } else if (node.children) { for (let i = 0; i < node.children.length; i++) { if (findAncestors(node.children[i], [...path, node])) { return true; } } } return false; // 未找到 } treeData.forEach(node => findAncestors(node)); return ancestors; } /** * @description 获取树形结构中某一节点的所有后代节点 */ getDescendants(id) { const descendants = []; function findDescendants(node) { if (node.children) { for (let i = 0; i < node.children.length; i++) { descendants.push(node.children[i]); if (node.children[i].children) { findDescendants(node.children[i]); } } } } function findNodeById(node) { if (node.id === id) { findDescendants(node); return true; } else if (node.children) { for (let i = 0; i < node.children.length; i++) { findNodeById(node.children[i]); return true; } } return false; } treeData.forEach(node => findNodeById(node)); return descendants; } /** * @description 获取树形结构中某一节点 * @param {*} treeData * @param {*} id * @returns */ getNodeById(treeData, id) { let nodeObj; function findNodeById(node) { if (node.id === id) { return node; } else if (node.children) { for (let i = 0; i < node.children.length; i++) { const foundNode = findNodeById(node.children[i]); if (foundNode) { return foundNode; } } } } for (let node of treeData) { nodeObj = findNodeById(node); break; } return nodeObj; } }