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 get key and values in an object

dasari yogini
Kilo Contributor

var obj = {
    prodUsers: {
        "aatest15": ["test016", "Test Automation 2"]
    },
    nonProdUsers: {
        "aatest14": ["test016", "Test Automation 2"]

    }
};

In this object aatest15 and aatest16 are users, test016 and Test Automation 2 are groups
how to check users are exist in user table or not and groups are exist in group table or not.

thanks

2 REPLIES 2

marcguegueniat
Kilo Sage

Hello,

This script should get you started.

var obj = {
    prodUsers: {
        "admin": ["test016", "Test Automation 2"]
    },
    nonProdUsers: {
        "aatest14": ["test016", "Test Automation 2"]

    }
};

for (var user in obj.prodUsers) {
  var groups = obj.prodUsers[user];
  if ( checkUser(user) ) {
    if ( checkGroups(groups ) ) {
      gs.print('user ' + user + ' exists and his groups exist');
    } else {
      gs.print('user ' + user + ' exists but one of his groups do not exist');
    }
  } else {
    gs.print('user ' + user + ' does not exist');
  }
}
for (var user in obj.nonProdUsers) {
  var groups = obj.nonProdUsers[user];
  if ( checkUser(user) ) {
    if ( checkGroups(groups ) ) {
      gs.print('user ' + user + ' exists and his groups exist');
    } else {
      gs.print('user ' + user + ' exists but one of his groups do not exist');
    }
  } else {
    gs.print('user ' + user + ' does not exist');
  }
}


function checkUser(user) {
  var userGr = new GlideRecord('sys_user');
  return userGr.get('user_name',user)
}

function checkGroups(groups) {

  for (var i =0; i<groups.length; i++) {
    var groupsGr = new GlideRecord('sys_user_group');
    if (!groupsGr.get('name', groups[i])) return false;
  }
  return true;
}

Regards,

Milind Gharte
Kilo Guru

Hi ,
Here is a link which will help you.

https://community.servicenow.com/community?id=community_blog&sys_id=b7603572db77130067a72926ca961910

 

If it helps,Please mark Correct and 👍 Helpful.

Warm Regards,

Milind