Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to check string key is available in a JavaScript object

chanikya
Kilo Sage

Hi All,

How to check system property stringKeys are available in Object Or Not ?
I have below Object & Property  :

var myObject = {
"name": "ServiceNow",
"version": "Quebec",
"Year":"2025",
"Country":"Canada"
};

system property: StringKeys
name, year

// ---I tried below script which is working fine--//
var fields = gs.getProperty("StringKeys").split(',');
for(var key in fields) {
  if(fields[key] in myObject) {
      gs.info("Success ");
   }
}


Can you help me is there better way to check string keys available in Object Or not ?



10 REPLIES 10

KrishnaMohan
Giga Sage

Hi @chanikya 

try below code

var myObject = {
"name": "ServiceNow",
"version": "Quebec",
"Year":"2025",
"Country":"Canada"
};


var fields =gs.getProperty("StringKeys");   // ex: "name,version"

 for (var key in myObject) {
        if (myObject.hasOwnProperty(key)) {
            if(fields.indexOf(key) != -1){
               gs.info(key + " is available in fields");
            }
        }}

 

If this helped to answer your query, please mark it helpful & accept the solution.
Thanks!
Krishnamohan

Hi @KrishnaMohan 

can we use below format ? if(fields[key] in myObject)  

 

var fields = gs.getProperty("StringKeys").split(',');
for(var key in fields) {
  if(fields[key] in myObject) {

 




what is the benefit if we use  below

 

myObject.hasOwnProperty(fields[key]);

 

 

M Iftikhar
Tera Sage

Hi Chanikya,

You can simplify your key check using hasOwnProperty and forEach like this:

var myObject = {
  "name": "ServiceNow",
  "version": "Quebec",
  "Year": "2025",
  "Country": "Canada"
};

gs.getProperty("StringKeys").split(',').forEach(function(key) {
    if (myObject.hasOwnProperty(key)) gs.info("Success: " + key + " exists");
});

This is cleaner, avoids for...in over arrays, and clearly shows which keys exist.

If you just want a single check for all keys:

var allExist = gs.getProperty("StringKeys").split(',').every(key => myObject.hasOwnProperty(key));
gs.info(allExist ? "All keys exist!" : "Some keys are missing!");

Using hasOwnProperty is the safest and most readable way to check object keys in ServiceNow scripts.
Hope this helps!

Thanks & Regards,
Muhammad Iftikhar
If my response helped, please mark it as the accepted solution so others can benefit as well.

Thanks & Regards,
Muhammad Iftikhar

If my response helped, please mark it as the accepted solution so others can benefit as well.

Hi @M Iftikhar 
can we use below format ? if(fields[key] in myObject)  

var fields = gs.getProperty("StringKeys").split(',');
for(var key in fields) {
  if(fields[key] in myObject) {




what is the benefit if we use  below

myObject.hasOwnProperty(fields[key]);