Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

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

@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  ||  10x ServiceNow MVP  ||  ServiceNow Community Leader