process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function (chunk) { const data = JSON.parse(chunk).employees; const employees = data.map((item) => ({...item, subordinates: []})); const buildHierarchy = (employees, managerId) => { return employees .filter(emp => emp.managerId == managerId) .map(emp => ({...emp, subordinates: buildHierarchy(employees, emp.id)})); } const result = buildHierarchy(employees, null); process.stdout.write(JSON.stringify(result, null, 2)); });
{ "employees": [ {"id": 1, "name": "Alice", "salary": 5000, "managerId": null}, {"id": 2, "name": "Bob", "salary": 4000, "managerId": 1}, {"id": 3, "name": "Charlie", "salary": 3000, "managerId": 1}, {"id": 4, "name": "David", "salary": 2500, "managerId": 2}, {"id": 5, "name": "Eve", "salary": 2000, "managerId": 2} ] }
[ { "id": 1, "name": "Alice", "salary": 5000, "managerId": null, "subordinates": [ { "id": 2, "name": "Bob", "salary": 4000, "managerId": 1, "subordinates": [ { "id": 4, "name": "David", "salary": 2500, "managerId": 2, "subordinates": [] }, { "id": 5, "name": "Eve", "salary": 2000, "managerId": 2, "subordinates": [] } ] }, { "id": 3, "name": "Charlie", "salary": 3000, "managerId": 1, "subordinates": [] } ] } ]