
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- JavaScript map value to keys (reverse object mapping)
- Mapping array of numbers to an object with corresponding char codes in JavaScript
- Mapping the letter of a string to an object of arrays - JavaScript
- Mapping unique characters of string to an array - JavaScript
- Mapping string to Numerals in JavaScript
- Mapping an array to a new array with default values in JavaScript
- Mapping values to keys JavaScript
- Write a program to reverse an array in JavaScript?
- Map an integer from decimal base to hexadecimal with custom mapping JavaScript
- Array reverse() in JavaScript
- How to reverse a portion of an array in JavaScript?
- Normalize numbers in an object - JavaScript
- Reverse numbers in function without using reverse() method in JavaScript
- JavaScript: Computing the average of an array after mapping each element to a value
- JavaScript Array reverse()

Advertisements