Search code examples
javascript-objectsdynamic-arraysservicenow

ServiceNow retrieving objects from array


I am working in ServiceNow and have an amateur coding question when it comes to objects, arrays, and how to access the elements. Below, I start with an empty array and populate it with objects. Now that I have an array with objects in them, my question is how do I access the different elements? I want to be able to generate a table where the columns are number, short_desc, and url, and the rows are produced dynamically. How am I able to accomplish this?

data.list = [];
var ka = new GlideRecord('x_81991_knowledge');
    ka.addQuery('kb_category.label', 'Benefits');
    ka.query();
        while(ka.next()) {
            data.list.push({
                number: ka.getValue('number'),
                short_desc: ka.getValue('short_description'),
                url:'kb_view.do?sysparm_article=' + ka.getValue('number')
          });
}

Solution

  • So, you've got an object: data, and in that object is an element: list. That element is an array, which contains other objects.

    Just as Objects in JavaScript contain properties with names, arrays are just like objects with properties that all have sequentially numbered names.

    For example, if you have an array like var fruitz = ['apple', 'banana', 'hammer', 'pear'];, it's very similar to having an object that looks like this:

    var fruitz = {
        0:'apple',
        1:'banana',
        3:'hammer',
        4:'pear'
    };
    

    In either example, you can access the element with the value 'banana' with: fruitz[1];.

    There are of course, several differences - including the fact that, of course, objects don't normally have properties with sequential numerical names! - this is JUST a good way to visualize how one would access array elements.

    Array elements in JS do retain their order, so an element in position 3 (the fourth element - remember, arrays use a "zero-based index") will remain at position 3.

    You could do a for-loop to iterate over and get elements from the array like so:

    var i;
    for (i = 0; i < fruitz.length; i++) {
        gs.info(fruitz[i] + ' is element number ' + i + ' in the array.');
    }
    

    There are some great resources online for learning Angular, which is definitely critical if you're looking to understand how the service portal works on the front-end.