GlideRecord using array values doesn't work

Andrew Bettcher
Kilo Sage

Hi,

I'm following this post (which I also commented on saying something like "Wow. It worked!!") to create a simply array that iterates through a list of choices and performs a glide record query using each of the items in an array like this:

 

var deviceTypes = [
'Laptop','SharePoint','PC'
];

for(var i in deviceTypes) {

var ciDevices = new GlideRecord('u_cmdb_ci_devices');
ciDevices.addEncodedQuery('u_device_type=' + deviceTypes[i]);
ciDevices.query();
}

while(ciDevices.next()) {
gs.print(ciDevices.u_device_type);
}

 

 

The problem is that the output (gs.print) just gives me one device type meaning that it isn't iterating through my array to perform the queries OR, it is but it's simply forgetting everything when it does the next one (i.e. because if I change the order of the array, it always prints the last one). There are definitely records that match all 3 device types and so I thought I'd get a ling list of device types (as many as there are records) but I don't.

I get this:

AndrewBettcher_0-1696932852811.png

What am I doing wrong?



1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@Andrew Bettcher 

the while should be within FOR

var deviceTypes = [
	'Laptop','SharePoint','PC'
];

for(var i in deviceTypes) {

	var ciDevices = new GlideRecord('u_cmdb_ci_devices');
	ciDevices.addEncodedQuery('u_device_type=' + deviceTypes[i]);
	ciDevices.query();
	while(ciDevices.next()) {
		gs.print(ciDevices.u_device_type);
	}
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

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

View solution in original post

5 REPLIES 5

Anil Lande
Kilo Patron

Hi,

Can you please try below:

var deviceTypes = [
'Laptop','SharePoint','PC'
];

for(var i in deviceTypes) {

var ciDevices = new GlideRecord('u_cmdb_ci_devices');
ciDevices.addEncodedQuery('u_device_type=' + deviceTypes[i]);
ciDevices.query();
while(ciDevices.next()) {
gs.print(ciDevices.u_device_type);
}
}

 

 

Your while loop was outside for loop so it was only printing last choice record valiues.

 

 

Please appreciate the efforts of community contributors by marking appropriate response as correct answer and helpful, this may help other community users to follow correct solution in future.
Thanks
Anil Lande