
- 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
JavaScript map value to keys (reverse object mapping)
We are required to write a function reverseObject() that takes in an object and returns an object where keys are mapped to values.
We will approach this by iterating over Object.keys() and pushing key value pair as value key pair in the new object.
Here is the code for doing so −
Example
const cities = { 'Jodhpur': 'Rajasthan','Alwar': 'Rajasthan','Mumbai': 'Maharasthra','Ahemdabad': 'Gujrat','Pune': 'Maharasthra' }; const reverseObject = (obj) => { const newObj = {}; Object.keys(obj).forEach(key => { if(newObj[obj[key]]){ newObj[obj[key]].push(key); }else{ newObj[obj[key]] = [key]; } }); return newObj; }; console.log(reverseObject(cities));
Output
The output of the above code in the console will be −
{ Rajasthan: [ 'Jodhpur', 'Alwar' ], Maharasthra: [ 'Mumbai', 'Pune' ], Gujrat: [ 'Ahemdabad' ] }
- Related Articles
- Reverse mapping an object in JavaScript
- Mapping values to keys JavaScript
- Changing value of nested object keys in JavaScript
- How to convert Map keys to an array in JavaScript?
- Map an integer from decimal base to hexadecimal with custom mapping JavaScript
- Map object in JavaScript.
- How can I instantiate a dictionary in JavaScript where all keys map to the same value?
- Object to Map conversion in JavaScript
- Convert object to a Map - JavaScript
- Recursively list nested object keys JavaScript
- Java Program to Sort map by keys
- JavaScript: How to remove the key-value pairs corresponding to the given keys from an object?
- How to use map() on an array in reverse order with JavaScript?
- Mapping the letter of a string to an object of arrays - JavaScript
- Compare keys & values in a JSON object when one object has extra keys in JavaScript

Advertisements