How to Create an array of GlideRecord objects?

chethann
Giga Contributor

Hi All,

I'm tried to copy the GlideRecord objects to an Array, so i can iterate through the array in HTML(view).

sample code -

var getHelpSupp = [];
var grSupp = new GlideRecord('u_get_help_support');
grSupp.addQuery('u_test_territory', lnk);
grSupp.orderBy('u_display_order');
grSupp.query();


while(grSupp.next()) {
//var test1 = grSupp;
getHelpSupp.push(grSupp);
}

// testing the data in array
for(var j=0; j<getHelpSupp.length; j++) {
var test = getHelpSupp[j];
console.log(test.u_support_label.getDisplayValue());
}

 

The query working fine, It fetching the 4 records from the table, the array size also a 4. but the issue all 4 records in the array is same, all are pointing to last record iterating in while loop GlideRecord.

It's some issue in copying the object in while it seems.

Anyone has faced same issue and has the solution pls.

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Chethan,

Following script you can try for example for pushing objects

var arr = [];

var gr = new GlideRecord('incident');
gr.setLimit(5);
gr.query();
while(gr.next()){

var obj = {};
obj.number = gr.number.toString(),
obj.shortDescription = gr.short_description.toString();


arr.push(obj);
}

gs.print(JSON.stringify(arr));

Mark Correct if this solves your issue and also hit Like and Helpful if you find my response worthy based on the impact.
Thanks
Ankur

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

View solution in original post

8 REPLIES 8

Sharique Azim
Mega Sage

I am just commenting on the logic of your script.

Shouldn't it be getHelpSupp.push(grSupp.some_field);  ??

 

 

im not sure with this script as this was not working while i tried to run, 

// testing the data in array
for(var j=0; j<getHelpSupp.length; j++) {
var test = getHelpSupp[j];
console.log(test.u_support_label.getDisplayValue()); // got error here
}

 

as Ankur suggested, you really have to create objects and JSON methods to access fields like this.

Gajanan Birada1
Giga Expert

Hi,

can you elaborate me in deeply ,i didn't understand  you got array date but it's all same like this

reginaldocosta
Tera Contributor

You should have the following supporting function:

function glideClone(current) {
    var sys_class_name = current.getValue('sys_class_name');
    var grnew = new GlideRecord(sys_class_name);
    for (prop in current) {
        grnew.setValue(prop, current.getValue(prop));
    }
    return grnew;
}

 

and use it on your loop..

var ARRAY = []; 
while (gr.next()) {
    ARRAY.push(glideClone(gr));
}

 

Vimal Jain
ServiceNow Employee
ServiceNow Employee