- 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
Mapping values to keys JavaScript
Suppose, we have an object like this −
const obj = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6 };
We are required to write a JavaScript function that takes in one such object. The function should reverse map the values to the keys of the object.
Therefore, for the above object, the output should look like −
const output = { '1': 'a', '2': 'b', '3': 'c', '4': 'd', '5': 'e', '6': 'f' };
Example
const obj = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6 }; const reverseMap = (obj = {}) => { const res = {}; Object.keys(obj).forEach(key => { const val = obj[key]; res[val] = key; }); return res; }; console.log(reverseMap(obj));
Output
And the output in the console will be −
{ '1': 'a', '2': 'b', '3': 'c', '4': 'd', '5': 'e', '6': 'f' }
- Related Articles
- JavaScript map value to keys (reverse object mapping)
- Fetching JavaScript keys by their values - JavaScript
- Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
- Mapping an array to a new array with default values in JavaScript
- The Keys and values method in Javascript
- Split keys and values into separate objects - JavaScript
- Mapping string to Numerals in JavaScript
- Compare keys & values in a JSON object when one object has extra keys in JavaScript
- Add values of matching keys in array of objects - JavaScript
- Iterate through Object keys and manipulate the key values in JavaScript
- Reverse mapping an object in JavaScript
- Mapping unique characters of string to an array - JavaScript
- URLSearchParams values & keys() in Node
- Building a Map from 2 arrays of values and keys in JavaScript
- JavaScript - Find keys for the matched values as like query in SQL

Advertisements