The CreatorCon Call for Content is officially open! Get started here.

Show all reportees / subordinates

Vicky Kumar Sha
Tera Contributor

I have some users in sys_user who are managers as well as they are under some manager. I need to create a function which given a user's sys_id, it should return a json object with all it's reportees under him/her  (direct and indirect). Using recursion

 

For ex: lets say we have 7 users

user1, user2, user3, user4, user5, user6, user7

user1 is manager of user2

user2 is manager of user3, user6

user3 is manager of user4, user5

user6 is manager of user7

If I pass user1's sys_id in the function

The function should return:

{
  "user1": {
    "user2": {
      "user3": [
        "user4",
        "user5"
      ],
      "user6": [
        "user7"
      ]
    }
  }
}
}
2 REPLIES 2

Mike_R
Kilo Patron
Kilo Patron

This is a good one. Can I ask what this will be used for/does it need to be in JSON? There's some code in the "Organization Chart" widget that should give you a good starting point

instanceName.service-now.com/nav_to.do?uri=sp_widget.do?sys_id=33b0f6f5c3310200b7b87868e1d3ae7b

 

Snippet from the server script

function createNodes() {
		var gr = new GlideRecord('sys_user');
		gr.get(start);
		data.start = start;
		data.name = gr.getDisplayValue('name');
		var n = data.nodes = [];
		// anchor user
		var u = getUser(gr);
		u.color = options.user_background_color;
		n.push(u);

		if (u.manager && gr.manager.active) {
			gr.get(u.manager);
			var m = getUser(gr);
			n.push(m);
			getSubs(u.manager, n, start);
		}

		getSubs(u.sys_id, n);

		function getSubs(manager, n, start) {
			var gr = new GlideRecord('sys_user');
			gr.addActiveQuery();
			gr.addQuery('manager', manager);
			gr.query();
			while (gr.next()) {
				var u = getUser(gr);

				if (start && u.sys_id == start)
					continue;

				n.push(u);
			}
		}

 

Doesn't work as required. This was a question I got in a interview and I need to show data in a JSON format as mentioned. If anyone has time I would like to attempt this question. Thanks