- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
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' ] }
Advertisements