Learn to convert a JS object to Map data structure in Javascript

Let's consider you have an object,

const author = {
  firstName: 'Param',
  lastName: 'Harrison'
};

To create a Map, you need array of key, value pairs. Example,

const profileMap = new Map([
  ['name', 'Param Harrison'],
  ['age', 30]
]);

// Get Name from the map
console.log(profileMap.get('name')); // Param Harrison
// set Age to the map
console.log('Old age -> ', profileMap.get('age')); // 30
profileMap.set('age', 20);
console.log('New age -> ', profileMap.get('age')); // 20

For more reading, you can check out our blog post about Map get and set methods.

So basically, you need to convert your object into an array of key, value pairs. It can get done through the Object.entries method.

// Convert object to array of key, value pairs
const authorArrayOfKeyValuePairs = Object.entries(author);
console.log(authorArrayOfKeyValuePairs);

// Output - [["firstName", "Param"],["lastName", "Harrison"]]

Now, we just need to pass the authorArrayOfKeyValuePairs value to the Map constructor.

// Create a Map
const mappedAuthor = new Map(authorArrayOfKeyValuePairs);
console.log(mappedAuthor.get('firstName'));

You can play around with the code in codesandbox,