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.

Need to push object in an array from loop

Surendra Deshmu
Tera Contributor

Hello Team,

 

Is there any way I can push Glide object as a value in an array-

 

Eg.

 

var users = [];
var a = new GlideRecord('sys_user');
a.addQuery('active',true);
a.setLimit(5);
a.query();
while(a.next()){

//*******************HERE I HAVE DOUBT

users.push(a);

//*******************

}
for(var index in users){
var inc = new GlideRecord('incident');
inc.initialize();
inc.caller_id = users.data[index].sys_id;
if(inc.insert()){
gs.info('INCIDENT is created '+inc.number);
}
}

 

For now there is only 1 value storing in an array, as it is object and not string I can't even use toString(), is there any way I can store all object records from loop in an array

1 ACCEPTED SOLUTION

Brad Bowman
Kilo Patron
Kilo Patron

Here's an example of how you can push an entire GlideRecord object into an array:

var users = [];
var obj = {};
var a = new GlideRecord('sys_user');
a.addQuery('active',true);
a.setLimit(5);
a.query();
while (a.next()) {
	for (var key in a) {
		obj[key] = a[key].toString();
	}
	users.push(obj);
}
gs.print(JSON.stringify(users));

View solution in original post

7 REPLIES 7

Thanks Brad,

This seems like something which I can use in my script.

 

I'll try it out . 

trying these steps and  still facing same issue. tried this very same code in scripts- background, even this code is not working as expected in scripts - background for  me. Pls help, is there any alternate way to push glide objects into array.

If anyone else is running into this, I had to move the declaration of the 'obj' variable inside of the while loop.