

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse mapping an object in 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. Let' say we have created a function findKey().
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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
Apple
- Related Questions & Answers
- JavaScript map value to keys (reverse object mapping)
- Mapping the letter of a string to an object of arrays - JavaScript
- Mapping array of numbers to an object with corresponding char codes in JavaScript
- Mapping unique characters of string to an array - JavaScript
- Mapping values to keys JavaScript
- Mapping string to Numerals in JavaScript
- Mapping an array to a new array with default values in JavaScript
- Map an integer from decimal base to hexadecimal with custom mapping JavaScript
- Write a program to reverse an array in JavaScript?
- Normalize numbers in an object - JavaScript
- Recursively flat an object JavaScript
- Array reverse() in JavaScript
- JavaScript Array reverse()
- How to reverse a portion of an array in JavaScript?
- How to access an object through another object in JavaScript?
Advertisements