How to dynamically dot-walk in script?

Gage
Tera Expert

I am trying to script a dynamic dot-walk. To simplify I have included the array of fields that includes a dot-walk in the script below.

var arrExample = ['first_name', 'last_name', 'location.city'];
var grUser = new GlideRecord('sys_user');
grUser.get('e663cd73db3fc7002fdfdd3b5e961970');

for (var i = 0; i < arrExample.length; i++){
    
    // Tried this, did not work
    //gs.log(grUser[arrExample[i]]);

    // Current workaround
    eval('gs.log(grUser.' + arrExample[i] + ');');

}

Current Background Script Output:

*** Script: John
*** Script: Smith
*** Script: Atlanta

I want to get this output without using the eval() statement if possible. Any help would be appreciated!

1 ACCEPTED SOLUTION

Gage
Tera Expert

getElement([dotwalk field]) appears to work. I am able to get the desired result without using an eval statement using the script below:

var arrExample = ['first_name', 'last_name', 'location.city'];
var grUser = new GlideRecord('sys_user');
grUser.get('e663cd73db3fc7002fdfdd3b5e961970');

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

    gs.log(grUser.getElement(arrExample[i]));

}

View solution in original post

5 REPLIES 5

Kyle Scharkopf
Tera Guru
Why did you put it in an array if there is only one record you are looking at?

Erik Gunther2
Kilo Guru

Try something like:

find_real_file.png

 

Both of these return the same value.

You could check to see if the "field" value has a "." in it. If it does then you parse it into 2 fields and use the [][] approach, otherwise you just use the [] approach. I hope this helps.

Gage
Tera Expert

getElement([dotwalk field]) appears to work. I am able to get the desired result without using an eval statement using the script below:

var arrExample = ['first_name', 'last_name', 'location.city'];
var grUser = new GlideRecord('sys_user');
grUser.get('e663cd73db3fc7002fdfdd3b5e961970');

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

    gs.log(grUser.getElement(arrExample[i]));

}