员工层次结构的递归函数(nodejs)

时间:2018-10-02 10:39:34

标签: node.js recursion callback

我表中的数据采用这种格式

emp_id,emp_name,title,supervisor_id,supervisor_name
11,Anant,Business Unit Executive,8,abc
15,Raina,Analysis Manager Senior,11,Anant
16,Kumar,Conversion Manager,11,Anant
18,amit,Analyst Specialist,11,Anant
25,anil,senior engineer,18,amit
35,Pang Pang,senior engineer,25,anil
38,Xiang Xiang,UE engineer,25,anil

我将输入supervisor_id,并将返回该雇员下的所有员工,然后继续执行此操作,直到达到较低级别,我想在具有递归功能的节点和sql服务器中执行此操作。

我希望这种数据采用这种分层结构。

var ds ={  'emp_id':11,
        'name': 'Anant',
        'title': 'Business Unit Executive',
        'children': [
          { 'name': 'Raina','emp_id':15, 'title': 'Analysis Manager Senior' },
          { 'name': 'Kumar','emp_id':16, 'title': 'Conversion Manager' },
          { 'name': 'amit', 'emp_id':18, 'title': 'Analyst Specialist',
            'children': [
              { 'name': 'anil','emp_id':25, 'title': 'senior engineer' ,            
                'children': [
                  { 'name': 'Pang Pang','emp_id':35, 'title': 'engineer' },
                  { 'name': 'Xiang Xiang', 'emp_id':38,'title': 'UE engineer' }
                ]
               }
             ]
           }
         ]
       };

1 个答案:

答案 0 :(得分:0)

我不熟悉您用于请求表单服务器的库,因此我将对这些部分进行sudo代码

async getEmployeesBySupervisorId(supervidor_id){
const employees = await <get-employees-query> // you may also need to map the results to your {emp_id, name, title} depending on your query library default to [] if no employees are found
return Promise.all(...employees.map(employee=>{
    employee.children = await getEmployeesBySupervisorId(employee.emp_id)
}))

}

这将使您拥有一系列带孩子的雇员,直到找不到更多雇员为止, 尽管此方法可以正常工作,但它会引发许多查询,但最好还是利用sql和ORM来提高效率,以备将来使用。