Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Finding director in management hierarchy

shill
Mega Sage

I am attempting to setup a script to navigate "up" the manager hierarchy to find the users Director.
We pass the users direct manager from an import and pass a "manager level" field that cooresponds to where you are in the org.
In this case, a Director has a manager level of 1.

Officially, there are only 3 levels below a Director, but, some levels manage others of the same level, so instead of just dot walking 3 levels to reach the Director record, it could be any number of levels.

I originally had three if statements to check three levels deep until I found a level 1.


function getDirector(user){
   
// get user's level and return nothing if Director or above   
var mgrl = user.u_manager_level;
   
     if (mgrl == '1' || mgrl == '3' || mgrl == '11' || mgrl == '0'){
           return "";
     }
   
     else if (user.manager.u_manager_level == '1'){
           return user.manager;
     }
     else if (user.manager.manager.u_manager_level == '1'){
           return user.manager.manager;
     }
     else if (user.manager.manager.manager.u_manager_level == '1'){
           return user.manager.manager.manager;
     }
}

This works fine except for those beyond 3 levels.
Besides just adding 2-3 more if statements and digging deeper, is there a way I can simplify this code to dot walk until I reach a level 1 manager regardless of how far I have to dig?
2 REPLIES 2

michael_baker
Tera Guru

The below function should do the trick. It uses a while loop to walk up to the manager record.



function getDirector(user){

// If user's manager level is a Director or above, return nothing
if (user.u_manager_level == '1' || user.u_manager_level == '3' || user.u_manager_level == '11' || user.u_manager_level == '0') {
return "";
}

// While user's manager level is not a Director, set user to manager and perform check
while (user.u_manager_level != '1') {
user = user.manager.getRefRecord();
}

return user;
}

Hope this helps!


shill
Mega Sage

I new there had to be a simple way to do this...
You solution never crossed my mind.