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

@Narayan K 

I believe I answered your original question.

In that you didn't mention there would be multiple values in 1 key

but this code should work for you

var prop = '{"LATAM":["Argentina","India","Brazil"],"EU":["UK","France"],"US":"United States"}';
var obj = JSON.parse(prop);
var searchValue = 'India';
var foundKey = null;

for (var key in obj) {
  var val = obj[key];
  if ((Array.isArray(val) && val.indexOf(searchValue) !== -1) ||
      val === searchValue) {
    foundKey = key;
    break;
  }
}

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

AnkurBawiskar_0-1749205494036.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

@Narayan K 

Any update to this?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

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);

       

    }

}

@Narayan K 

I believe I answered your both the questions the original one and subsequent one.

Any reason you marked your own response as correct?

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

@Narayan K 

Any update to this?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader