How to get Key by passing Value?

Narayan K
Tera Expert

Hi there,

 

I have created system property with key value pair. In script I can return value by passing key but is it possible to return key by passing value?

 

Thanks!

1 ACCEPTED SOLUTION

Resolved:



var propertyValue = gs.getProperty('testproperty');

//{"LATAM":["Argentina", "India", "Brazil"]}

var regionMap = JSON.parse(propertyValue);



var targetCountry = 'India';



for (var region in regionMap) {

    var countries = regionMap[region];

    if (countries.indexOf(targetCountry) !== -1) {

        gs.info("country" + targetCountry + "has region " + region);

       

    }

}

View solution in original post

9 REPLIES 9

Anil Nemmikanti
Giga Guru
Giga Guru

Hi @Narayan K ,

Please use the system property in JSON key pair values. In that way you can get key based on value.

Nayan  Dhamane
Kilo Sage

Hello Kindly see below script which might help you:

var propertyValue = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
};
//var jsonObject = JSON.parse(propertyValue);
var searchValue = 'value2';
var foundKey = null;
for (var key in propertyValue) {
if (propertyValue[key] === searchValue) {
foundKey = key;
break;
}
}

if (foundKey) {
gs.info('Found key: ' + foundKey);
} else {
gs.info('Value not found');
}
If my answer solved your issue, please mark my answer as Correct & Helpful based on the Impact

Best Regards,
Nayan Dhamane
ServiceNow Community Rising Star 2023.

Ankur Bawiskar
Tera Patron
Tera Patron

@Narayan K 

something like this can help you get started

Ensure you use system property value but I hard-coded the json string

//var prop = gs.getProperty('my_property'); // Replace with your property name
var prop = '{"US":"United States","IN":"India","UK":"United Kingdom"}';
var obj = JSON.parse(prop);
var searchValue = 'India'; // The value you want to find the key for
var foundKey = null;

for (var key in obj) {
  if (obj[key] == searchValue) {
    foundKey = key;
    break;
  }
}

gs.info('Key for value "' + searchValue + '" is: ' + foundKey);

Output:

AnkurBawiskar_0-1749201012846.png

 

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

Hi @Ankur Bawiskar ,

 

Thanks for the solution. I am able to get Key by using value but currently I am storing multiple values for a single key as shown below:

 

{"LATAM":["Argentina","India","Brazil"]}

 

Given code is not working for multiple country values.