Arrays of Incidents

Jamsta1912
Tera Guru

Hello all,

I'm after some advice on how to add incident objects to an array from a glide query. Or, I'd like to be told that this is a bad idea, if that's the case!

I can create an array to store the sys_id as a string. And then use that sys_id to later get the incident and manipulate it or lookup values etc.

But, I was wondering it's a better or worse practice to store the whole object in the array from the start and then avoid having to get the incident later.

The example code below doesn't work and I've got my head around why: inc gets updated as we loop through the query results, and each element of the array is holding a reference to whatever inc is referencing, so each element ends up with the last value. So my question is: is there a way to add a reference to the actual incident inc is referencing at the time (the whole incident, not just the sys_id)?

var arr = [];

var inc = new GlideRecord('incident');

inc.addQuery('active', true);

inc.query();

while (inc.next()){

  arr.push(inc);

}

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

  gs.print('item ' + i + ' number is ' + arr[i].number);

}

1 ACCEPTED SOLUTION

Hello Jamie,



Thank you very much!



I'm very sorry, I completely missed that.



But good news, I think I found a way to do it. I tested this code and it seems to be working:



var gObjects= new GlideRecord('incident');


gObjects.addQuery('active', true);


gObjects.query();




var objArray = [];




while(gObjects.next()){




      var newObj = {};


      for (var key in gObjects) {


              //copy all the fields


              newObj [key] = gObjects[key];


      }




      objArray.push(newObj);




}








Thank you.


View solution in original post

7 REPLIES 7

Hello Jamie,



Thank you very much!



I'm very sorry, I completely missed that.



But good news, I think I found a way to do it. I tested this code and it seems to be working:



var gObjects= new GlideRecord('incident');


gObjects.addQuery('active', true);


gObjects.query();




var objArray = [];




while(gObjects.next()){




      var newObj = {};


      for (var key in gObjects) {


              //copy all the fields


              newObj [key] = gObjects[key];


      }




      objArray.push(newObj);




}








Thank you.


Thank you! This is a really useful technique.


Hi Edwin,



Can u elaborate more on this. Bcz i tried this and still i m getting the final reference and same values same as arr.push(inc).


What is meant by copy all fields?. Can u provide the complete example?. I want to store the complete incident objects in an array.