JavaScript map value to keys (reverse object mapping)

JavascriptWeb DevelopmentObject Oriented Programming

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' ]
}
raja
Published on 19-Aug-2020 10:52:07
Advertisements