Suppose we have an object like this −
const obj = { name: "Vikas", age: 45, occupation: "Frontend Developer", address: "Tilak Nagar, New Delhi", experience: 23, };
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
Let's write the code for this −
const obj = { name: "Vikas", age: 45, occupation: "Frontend Developer", address: "Tilak Nagar, New Delhi", experience: 23, salary: "98000" }; 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(6) { 'name' => 'Vikas', 'age' => 45, 'occupation' => 'Frontend Developer', 'address' => 'Tilak Nagar, New Delhi', 'experience' => 23, 'salary' => '98000' }