Function required to find all childs of the parent on same table

ramandeepgarg6
Tera Expert

Hi Friends,

I have a "Department" table which contains a "Parent Department" field. See below screenshot. If I select department as 'A' then it should get all children as [A, B, C, BB1, BB2, CC1, CC2].

I have written below code but it is not working properly and it is not able to find all the departments. Could you please help?

getChildDepartment: function(dep, finalArr) {
var gr = new GlideRecord('u_cmn_department');
gr.addQuery('u_parent', dep);
gr.query();
while(gr.next()){
finalArr.push(gr.sys_id);
this._getChildDepartment(gr.sys_id, finalArr);
}
return finalArr;
},

Regards

Ramandeep

1 ACCEPTED SOLUTION

This is all you need.


I hope the table name i have put is correct 'cmn_department'


Try running the below script in Background Script



getChildDepartment('enter your department name here');


function getChildDepartment(dep)


{


var finalArr = [];


var gr = new GlideRecord('cmn_department');


gr.addQuery('u_parent.name', dep);


gr.query();


while(gr.next()){


finalArr.push(gr.sys_id);


while (gr.u_parent!='')


gs.addInfoMessage(gr.name);


        this.getChildDepartment(gr.name);


}



return finalArr;


}



Please mark this response as correct or helpful if it assisted you with your question.

View solution in original post

14 REPLIES 14

ramandeepgarg6
Tera Expert

parent-child.png


Try below code



getChildDepartment: function(dep) {


var finalArr = [];


var gr = new GlideRecord('cmn_department');


gr.addQuery('u_parent', dep);


gr.query();


while(gr.next()){


finalArr.push(gr.sys_id);


// this._getChildDepartment(gr.sys_id, finalArr);


}


return finalArr;


},



Please mark this response as correct or helpful if it assisted you with your question.

Hi sanjiv,



The code you mentioned below will return only "B" and "C".



Regards


Ramandeep


getChildDepartment: function(dep) {


var finalArr = [];


var gr = new GlideRecord('cmn_department');


gr.addQuery('u_parent', dep);


gr.query();


while(gr.next()){


finalArr.push(gr.sys_id);


if (gr.u_parent!='')


        this._getChildDepartment(gr.sys_id);


}


return finalArr;


},



Please mark this response as correct or helpful if it assisted you with your question.