Object to Map conversion in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an object like this −

const obj = {
   name: "Jai",
   age: 32,
   occupation: "Software Engineer",
   address: "Dhindosh, Maharasthra",
   salary: "146000"
};

We are required to write a JavaScript function that takes in such an object with key value pairs and converts it into a Map.

Example

The code for this will be −

const obj = {
   name: "Jai",
   age: 32,
   occupation: "Software Engineer",
   address: "Dhindosh, Maharasthra",
   salary: "146000"
};
const objectToMap = obj => {
   const keys = Object.keys(obj);
   const map = new Map();
   for(let i = 0; i < keys.length; i++){
      //inserting new key value pair inside map
      map.set(keys[i], obj[keys[i]]);
   };
   return map;
};
console.log(objectToMap(obj));

Output

The output in the console −

Map(5) {
   'name' => 'Jai',
   'age' => 32,
   'occupation' => 'Software Engineer',
   'address' => 'Dhindosh, Maharasthra',
   'salary' => '146000'
}
raja
Published on 15-Oct-2020 08:58:27
Advertisements