While loop is only pushing 1st value inside array

Mit1008
Tera Contributor

While loop is only pushing 1st value inside array 

var arr=[];
function test() {
    
    var grUpdateApprover = new GlideRecord('sys_user_grmember');
    grUpdateApprover.addEncodedQuery('group=0a52d3dcd7011200f2d224837e6103f2');
    grUpdateApprover.query();
    while (grUpdateApprover.next()) {
        arr.push(grUpdateApprover.user);
    }
    gs.info(arr.toString());
}

test();

 

I tested this in background script.

3 REPLIES 3

nv147
Tera Expert

Replace

arr.push(grUpdateApprover.user);

With this:

arr.push(grUpdateApprover.user.toString());

Just to clarify, when you're pushing the grUpdateApprover.user, that's a GlideRecord object. That object isn't actually changing each time your loop calls next(); The data inside it is what's changing

 

So, you're pushing that user GlideRecord object into your array four times, and then your loop updates it to the last user. So, when you go to print out your array, all objects point to the same user.

 

This is why it's often important to be specific with what type you're using: In this case, you want the sysid (a string) so toString() works, a String() wrapper works, etc.

Juhi Poddar
Kilo Patron

Hello @Mit1008 

To meet the requirements, please refer to my solution in this thread While loop is only pushing 1st value inside array

Hope this helps!

 

If this helped, please hit like and mark it as an accepted solution.

 

Thank You 

Juhi Poddar