Fetching JavaScript keys by their values - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an object like this −

const products = {
   "Pineapple":38,
   "Apple":110,
   "Pear":109
};

All the keys are unique in themselves and all the values are unique in themselves. We are required to write a function that accepts a value and returns its key

For example: findKey(110) should return −

"Apple"

We will approach this problem by first reverse mapping the values to keys and then simply using object notations to find their values.

Example

Following is the code −

const products = {
   "Pineapple":38,
   "Apple":110,
   "Pear":109
};
const findKey = (obj, val) => {
   const res = {};
   Object.keys(obj).map(key => {
      res[obj[key]] = key;
   });
   // if the value is not present in the object
   // return false
   return res[val] || false;
};
console.log(findKey(products, 110));

Output

This will produce the following output in console −

Apple
raja
Published on 18-Sep-2020 13:14:25
Advertisements