- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Fetching JavaScript keys by their values - JavaScript
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
- Related Articles
- Fetching object keys using recursion in JavaScript
- Mapping values to keys JavaScript
- The Keys and values method in Javascript
- Split keys and values into separate objects - JavaScript
- Filter nested object by keys using JavaScript
- How to generate child keys by parent keys in array JavaScript?
- Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
- Fetching odd appearance number in JavaScript
- Add values of matching keys in array of objects - JavaScript
- Compare keys & values in a JSON object when one object has extra keys in JavaScript
- Iterate through Object keys and manipulate the key values in JavaScript
- Building a Map from 2 arrays of values and keys in JavaScript
- JavaScript - Find keys for the matched values as like query in SQL
- Group array by equal values JavaScript
- Sorting objects by numeric values - JavaScript

Advertisements