Split array and use elements in GlideRecord

Puru2
Tera Contributor

Dear All,

I want to split the array and use its stored elements in GlideRecord query.

Below mentioned is the code snippet :

// str contains 2 sys_ids  as  -> [*sys_id_1*, *sys_id_2*] 
for(var i=0;i<str.length;i++)
{

var rec = new GlideRecord('core_country');
rec.addQuery('sys_id',str[i]);  // trying to query a record via first sys_id
rec.query();
while(rec.next())
{

// perform action

}

 

Please  suggest me any possible corrections in this code snippet.

 

Best Regards,

Puru

 

 

8 REPLIES 8

Hi Puru,

 

ChrisB  has made a valid point i think. focus on pt 1.

 

btw in case you are querying like 

 

for(var i=0;i<str.length;i++)
{

var rec = new GlideRecord('core_country');
rec.addQuery('sys_id',str[i]);  

rec.query();
if(rec.next()) //use if  instead of while, as you are already within a for loop
{

  // perform action
}

 

 

also as correctly mentioned by dinnex, you need to create array of strings first.

suppose ,var str=["sys_1,sys_2,..."]; is used your code will work,

 

but if your str variable is just comma seperated string,then you first need to convert it into array first.

 

eg. ,

var str="sys_1,sys_2,...";

var arr =str.split(',');

for(var i=0;i<arr.length;i++)
{

var rec = new GlideRecord('core_country');
rec.addQuery('sys_id',arr[i]);  

rec.query();
if(rec.next()) //use if  instead of while, as you are already within a for loop
{

  // perform action
}

any updates on this?

 

Dinesh Nikam
Mega Guru

Hello Puru,

        As you said you are taking sys_id's of countries from another table(records of core_country table). so you just try this code for pushing sys_id's to the array.

var str=[];

var gr = new GlideRecord('table_name');

gr.query();

while(gr.next())
{


str.push(gr.getValue('sys_id'));

}

 

------And Your code is correct------

 

for(var i=0;i<str.length;i++)
{

var rec = new GlideRecord('core_country');
rec.addQuery('sys_id',str[i]);  // trying to query a record via first sys_id
rec.query();
while(rec.next())
{

// perform action

}

 

 

 

*****************PLEASE mark my ANSWER as CORRECT if it served your purpose.******************

 

AkshayPunekar31
Mega Expert

Hi Puru,

Refer the code below:

for(var i=0;i<str.length;i++)
{
  var rec = new GlideRecord('core_country');
  rec.addQuery('sys_id','IN',str[i]);
  rec.query();
  while(rec.next())
  {
    // perform action
  }

}

Let me know the change in behavior of code.


Please mark reply as Helpful/Correct, if applicable. Thanks!

Warm Regards,

Akshay Punekar

find_real_file.png

www.dxsherpa.com