Based on value need to fetch key in a array

Vijay Kumar21
Tera Contributor

Hi Team,

I have an Array 'arr' and i already have a value as '4', Now I need to fetch only the specific Key from the value (I need 'Yes' from '4' in an array)

arr = {"Yes":"4","Limited":"3","Unvalidated":"2","No":"1","-":"0"}

could anyone please provide there suggention ?

1 ACCEPTED SOLUTION

Aman Kumar S
Kilo Patron

Hey,

You can use below approach:

This is from geeksforgeeks.

Basically getKeyByValue function we can pass the object that your have and the value you are searching for, it will return you the key.

 var exampleObject = {
            key1: 'Geeks',
            key2: 100,
            key3: 'Javascript'
        };
ans = gs.info(getKeyByValue(exampleObject, 100));
function getKeyByValue(object, value) {
       for (var prop in object) {
           if (object.hasOwnProperty(prop)) {
               if (object[prop] === value)
                 return prop;
           }
        }
 }

.Output : key2

 

Feel free to mark correct, If I answered your query.

Will be helpful for future visitors looking for similar questions 🙂

Best Regards
Aman Kumar

View solution in original post

4 REPLIES 4

Aman Kumar S
Kilo Patron

Hey,

You can use below approach:

This is from geeksforgeeks.

Basically getKeyByValue function we can pass the object that your have and the value you are searching for, it will return you the key.

 var exampleObject = {
            key1: 'Geeks',
            key2: 100,
            key3: 'Javascript'
        };
ans = gs.info(getKeyByValue(exampleObject, 100));
function getKeyByValue(object, value) {
       for (var prop in object) {
           if (object.hasOwnProperty(prop)) {
               if (object[prop] === value)
                 return prop;
           }
        }
 }

.Output : key2

 

Feel free to mark correct, If I answered your query.

Will be helpful for future visitors looking for similar questions 🙂

Best Regards
Aman Kumar

Mahesh23
Mega Sage

Hi,

Its not an array its object. In order to access only value you can try below code

arr = {"Yes":"4","Limited":"3","Unvalidated":"2","No":"1","-":"0"}
gs.log(arr.Yes)

Output:
4

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

sample script

var arr = {"Yes":"4","Limited":"3","Unvalidated":"2","No":"1","-":"0"};

var myKeyName = getKey(4,arr);

gs.info(myKeyName);

function getKey(val,array){
    for (var key in array) {
        if(array[key] == val){
            return key;
        }
    }
 return false;
}

Output:

find_real_file.png

Regards
Ankur

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

Mahesh23
Mega Sage

Hi,

Try below code

var arr = {"Yes":"4","Limited":"3","Unvalidated":"2","No":"1","-":"0"}

gs.log(Object.keys(arr));
gs.log(Object.keys(arr)[0]);

find_real_file.png