How to iterate array using for loop and pass each value in a object
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-17-2024 12:46 AM
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
*** Script: output1 : 0e3b835b1b38d910ceaa20e23b4bcbda test 2
*** Script: output2 : test 2
5 REPLIES 5
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-17-2024 01:33 AM
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
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader