How to iterate array using for loop and pass each value in a gliderecord

Laukik Udpikar
Tera Expert

Hello Experts,

I need help in below script;

arr = ['sysid,'sysid'];

I want to create a for loop and get each sysid to be passed in a gliderecord and add each value as part of encodeded query as well,

Need help in building it

1 ACCEPTED SOLUTION

Hi,

by iterating every sysId you want to fetch the child

do like this

var arr = ['sysid1','sysid2'];

var child = [];

for(var i in arr){
	var gr = new GlideRecord('table');
	gr.addEncodedQuery('parent!=NULL^active=true^parent=' + arr[i]);
	gr.query();
	while(gr.next()){
		child.push(gr.sys_id.toString());
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

8 REPLIES 8

Hi Ankur,

thanks for the response, but I need to iterate through each sysid of array, and not search only single match from array.

 

Hi,

by iterating every sysId you want to fetch the child

do like this

var arr = ['sysid1','sysid2'];

var child = [];

for(var i in arr){
	var gr = new GlideRecord('table');
	gr.addEncodedQuery('parent!=NULL^active=true^parent=' + arr[i]);
	gr.query();
	while(gr.next()){
		child.push(gr.sys_id.toString());
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

The previous example was better. It was searching the entire array all at once using parentIN, which should satisfy the requirement of getting all items where the sys_id is listed as the parent. one query is better than array.length queries.

This can be simplified using a glidequery, too:

arr = ['sysid1','sysid2']

var child = new GlideQuery('table')
.where('active', true)
.where('number', '!=', 'NULL')
.where('number','IN',arr)
.select()
.map(function(e) {
  return e.sys_id;
})
.toArray(100);

gs.info(child)

/*
example returns
[
  "9e7f9864532023004247ddeeff7b121f",
  "552c48888c033300964f4932b03eb092"
]
*/

Ankur again for the win. I had:

for (var i = 0; i < array.length; i++)

and it wasn't working. I found this post and, cross checking with the comments here changed my code to:

for (var i in arr)

and, like magic, it all started working.

I didn't ever really understand what that first statement was actually saying but it's all a little clearer now.

Don't go away though. I might need you.....;-)