Computer >> Computer tutorials >  >> Programming >> Javascript

Get key from value in JavaScript


Suppose, we have an object of arrays like this −

const obj = {
   'key1': ['value11', 'value12', 'value13', 'value14', 'value15'],
   'key2': ['value21', 'value22', 'value23', 'value24', 'value25',
   'value26', 'value27'],
   'key3': ['value31', 'value32', 'value33', 'value34'],
   'key4': ['value41', 'value42'],
};

We are required to write a JavaScript function that takes in one such object as the first argument and a value string as the second argument. The function then should check to which key the input value belongs.

for 'value13', the key will be 'key1'
for 'value32', the key will be 'key3'

Example

The code for this will be −

const obj = {
   'key1': ['value11', 'value12', 'value13', 'value14', 'value15'],
   'key2': ['value21', 'value22', 'value23', 'value24', 'value25',
   'value26', 'value27'],
   'key3': ['value31', 'value32', 'value33', 'value34'],
   'key4': ['value41', 'value42'],
};
const searchByValue = (obj, val) => {
   for (let key in obj) {
      if (obj[key].indexOf(val) !== -1) {
         return key;
      };
   };
   return null;
};
console.log(searchByValue(obj, 'value32'));

Output

And the output in the console will be −

key3