如何通过递归实现员工组织层级结构的打印?
组织架构图递归打印实现方案
问题概述
你已经成功将员工数据转换为包含details(角色、地点)和reports(下属列表)的对象结构,现在需要通过递归遍历该结构,按照层级缩进打印出符合要求的组织架构图。
完整实现代码
function printOrgChart(employeeData) { const results = {}; const formatted = employeeData.map((employee) => employee.split(',')); for (let i = 0; i < formatted.length; i++) { let person = formatted[i][0]; let manager = formatted[i][1]; let role = formatted[i][2]; let location = formatted[i][3]; // 维护经理的下属列表 if (results.hasOwnProperty(manager)) { results[manager]['reports'].push(person); } else { results[manager] = { details: [], reports: [person], }; } // 维护当前员工的详情(修复重复添加问题) if (results.hasOwnProperty(person)) { results[person]['details'] = [role, location]; } else { results[person] = { details: [role, location], reports: [], }; } } // 递归打印层级结构的核心函数 function printHierarchy(employeeName, level = 0) { // 按层级生成缩进空格,每级3个空格 const indent = ' '.repeat(level); const { details: [role, location] } = results[employeeName]; // 根节点去除开头多余空格 console.log(`${indent}${employeeName} [${role}, ${location}]`.trimStart()); // 遍历所有下属,递归打印下一层级 results[employeeName].reports.forEach(report => { printHierarchy(report, level + 1); }); } // 定位组织根节点(经理为自身的员工,即最高负责人) const rootEmployee = Object.keys(results).find(name => results[name].reports.includes(name)); printHierarchy(rootEmployee); } // 测试用员工数据 const employeeData = [ 'Alice,Heidi,Engineering Manager,Vancouver', 'Bob,Grace,Product Director,SF', 'Charlie,Bob,Product Manager,Tempe', 'David,Alice,Software Developer,Bangalore', 'Eve,Heidi,Principal Engineer,SF', 'Frank,Bob,Designer,SF', 'Grace,Grace,CEO,SF', 'Heidi,Grace,CTO,SF', 'Ivan,Grace,Operations Director,SF', ]; printOrgChart(employeeData);
关键逻辑说明
- 数据结构优化:原代码中重复处理员工时会多次向
details推送数据,改为直接赋值避免冗余。 - 递归函数设计:
printHierarchy函数接收当前员工名称和层级参数,层级默认0对应根节点- 用
' '.repeat(level)生成对应层级的缩进空格,匹配示例格式 - 打印当前员工的完整信息,根节点通过
trimStart()去除多余开头空格 - 遍历当前员工的下属列表,递归调用自身并将层级+1,实现嵌套缩进效果
- 根节点定位:通过
find方法找到"经理是自己"的员工,作为递归遍历的起点。
输出效果
运行代码后会输出符合要求的组织架构:
Grace [CEO, SF] Bob [Product Director, SF] Charlie [Product Manager, Tempe] Frank [Designer, SF] Heidi [CTO, SF] Alice [Engineering Manager, Vancouver] David [Software Developer, Bangalore] Eve [Principal Engineer, SF] Ivan [Operations Director, SF]
内容的提问来源于stack exchange,提问作者clowniecat
相关产品推荐
相关产品推荐

