Script on reference qualifier using an array.push() go wrong

John91
Tera Contributor

Hi,

This may be a newbie script question but this is annoying for me.

I wrote the script below in the reference qualifier of a group field, but it doesn't work.

-----------------

javascript: 
var gr2 = new GlideRecord("sys_user_group");
gr2.addQuery("type", "CONTAINS", "791a35c11b68dd1088c1553b234bcb55");
gr2.query();
    var arr = [] ;
    var i = 0 ;
    while (gr2.next()) {
        arr.push(gr2.sys_id) ;
        gs.addInfoMessage(i-1 + " : " + arr[i-1]);
        gs.addInfoMessage(i + " : " + arr[i]);
        i ++;
    }
    gs.addInfoMessage("afterpush 0 :" + arr[0]);
    gs.addInfoMessage("afterpush 1 :" + arr[1]);
    "sys_idIN" + arr ;

-----------------

and the results of the messages are below;

-----------------

-1 : undefined
0 : 3a1e054b1bc0d9103967217b234bcb2f
0 : 730ec54b1bc0d9103967217b234bcba7
1 : 730ec54b1bc0d9103967217b234bcba7
afterpush 0 :730ec54b1bc0d9103967217b234bcba7
afterpush 1 :730ec54b1bc0d9103967217b234bcba7

-----------------

I don't get even though "arr.push" is executed twice but the single sysid is in index 0 and 1.
I guess "push" should add new values in an array...

Please tell me how I should write. 

Thanks

1 ACCEPTED SOLUTION

MrMuhammad
Giga Sage

Hi John,

This is expected behavior and logically correct. When you push GlideRecord referenced data into array it passes stores the reference of the object into the array instead of the value you are passing so the idea is to store the value that can be achieved by explicitly converting the value to toString before storing into the array

arr.push(gr2.sys_id.toString()) ;

or 

use Servicenow given methods which is the preferred way of retrieving value as a string.

arr.push(gr2.getValue("sys_id")) ;

KB Article https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0858268

Read more on this topic here Pass by Value vs Pass by reference

Regards,

Muhammad

Regards,
Muhammad

View solution in original post

8 REPLIES 8

Mohith Devatte
Tera Sage
Tera Sage

Hello,

Please use .toString()  while pushing the sys_id into array like below

  arr.push(gr2.sys_id.toString());

Please try this and if it only works or helps you mark it correct answer

thanks

Hi Mohith,

Thanks for your quick reply, and this is great!

However, I can't understand the cause. Could you tell me?

Harshad Wagh
Tera Guru

try this which somehow have helped me in past.

 

 arr.push(gr2.sys_id.toString()) ;

 

OR

 arr.push(gr2.getUniqueValue()) ;

 

Thanks

Harshad

 

 

 

Hello Harshad,

Thank you for your quick reply, and it did work well!

But I don't know why.. Could you tell me the reason?
"arr" has no specific data type, so I guess this is the cause. Is it right?