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.

How to iterate array using for loop and pass each value in a object

Priyadharashin1
Tera Contributor

Hello

 

I have the below script to iterate over an array and pass it to an object. But outside the for loop , I get a single value alone

Please provide some suggestion.

 

var id = ['0beb47131b78d910ceaa20e23b4bcb24', '0e3b835b1b38d910ceaa20e23b4bcbda'];

var name = [];
for (var i in id) {
    var gr = new GlideRecord("table");
    gr.get(id[i]);
    name = gr.u_name.toString();
    obj = {
        txt: name
    };

     gs.info('output 1: ' + id[i] + name);
}
//  return name;
gs.info('output 2: ' + obj.txt);
 
output:
** Script: output1 : 0beb47131b78d910ceaa20e23b4bcb24 test
*** Script: output1 : 0e3b835b1b38d910ceaa20e23b4bcbda test 2
*** Script: output2 : test 2
5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

@Priyadharashin1 

use this

var id = ['0beb47131b78d910ceaa20e23b4bcb24', '0e3b835b1b38d910ceaa20e23b4bcbda'];
var nameArr = [];
for (var i in id) {
    var gr = new GlideRecord("table");
    if (gr.get(id[i])) {
        var name = gr.getValue('u_name');
        nameArr.push(name);
    }
}
gs.info('output 2: ' + nameArr.toString());

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