How To Convert Map To Object In JavaScript

JavaScript provides various built-in data structures for storing data. One such data structure is a Map object that stores key-value pairs, similar to an object. However, in certain scenarios, we may need to convert a Map object to a regular object.

In this article, we will discuss different approaches for converting Map to Object in JavaScript. When choosing the final approach, we should consider the following factors such as the size of the Map object, performance requirements and personal preference.

Need for converting map to object in JavaScript

Converting Map to Object can be useful in the following scenarios:

  • Serialisation: When we want to serialise a Map object to JSON format, as JSON can only serialise regular objects.
  • Merging maps: When we want to merge multiple Maps into a single object.
  • Performing different operations: When we want to perform operations like sorting, filtering, or mapping on a Map object that requires an object.

Different Approaches on how to convert map to object in Javascript

There are several different approaches for converting a Map to an Object in JavaScript:

  1. Using the spread operator.
  2. Using the Array.reduce() method.
  3. Using a loop.

Approach 1: Using the spread operator

It utilises the spread operator and the Object.fromEntries() method to make a new object with the key-value pairs from the Map object, which allows us to easily convert Map to object in just a few lines of code.

This method is efficient and straightforward, making it a popular choice among developers.

Sample Code:

// input
const map = new Map([
  ['name', 'Natasha'],
  ['age', 27],
  ['gender', 'female']
]);

// convert the Map object to an array of key-value pairs
const obj = { ...Object.fromEntries(map) };
console.log(obj);

Output:

{ name: Natasha, age: 27, gender: 'female' }

Code Explanation:

  • We first create a Map object named map with three key-value pairs.
  • We use the Object.fromEntries() method to transform the Map object to an array of key-value pairs and then use the spread operator to spread these pairs into a new object named obj.
  • The resulting object obj contains the same keys and values as the original Map object.

Approach 2: Using the Array.reduce() method

The Array.reduce() function is used for iterating over a Map object to create a new object and then copying the key-value pairs to the new object. It provides a powerful way to convert a Map to an Object while also allowing for more complex data manipulation.

This method is ideal for situations where you need to perform more advanced data processing.

Sample Code:

// input
const map = new Map([
  ['name', ‘Eric’],
  ['age', 30],
  ['gender', 'male']
]);

//convert the Map object to an array of key-value pairs and then use the reduce() method to iterate 
// over this array
const obj = Array.from(map).reduce((obj, [key, value]) => {
  obj[key] = value;
  return obj;
}, {});

console.log(obj);

Output:

{ name: 'Eric', age: 30, gender: 'male' }

Code Explanation:

  • We first create a Map object named map with three key-value pairs.
  • The Array.from() method is used to turn the map object into array of key-value pairs
  • Then we use the reduce() function to iterate over the array and copy the key-value pairs into a variable “obj” (the new object).
  • The reduce() method takes two arguments: a callback function that performs the copying of key-value pairs, and an initial value for the new object obj.
  • The resulting object obj contains the same keys and values as the original Map object.

Approach 3: Using a loop

This method utilises a loop to iterate over key-value pairs of the Map object and copy them to a new object. This method is more manual and requires more lines of code.

Though it can be handy in situations where you need to customise the conversion process to meet specific requirements.

Sample Code:

function mapToObject3(map) {
  let obj = {};

// iterate over each entry in the Map using the for...of loop
  for (let [key, value] of map) {
    obj[key] = value;
  }
  return obj;
}

//  input
const myMap = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);
const myObject = mapToObject3(myMap);
console.log(myObject);

Output:

{ foo: 'bar', baz: 42 }

Code Explanation:

  • We create an empty object using the let obj = {} statement.
  • We iterate over each entry in the Map using the for…of loop. The let [key, value] syntax extracts the key and value from each entry.
  • For each entry, we add a property to the new object using the obj[key] = value syntax.
  • Finally, we return the new object.

Best Approach for “how to change Map to object in JavaScript”

The best approach for converting an object to a Map in JavaScript is to use the spread operator approach due to the following reasons:

  • Concise and easy: Using the spread operator is the most concise and easiest to read approach.
  • Less code required: The Array.reduce() method is flexible but can be more verbose and requires more code compared to the spread operator approach.
  • Less complexity: Using a loop is a very manual approach and requires the most code which can make it more error-prone and harder to maintain.

Sample Problems on how to convert map to object in javascript

Sample Problem 1: Using the spread operator

You are working on creating a website that provides information about different countries around the world with their capital cities. You have data stored in a Map called countryCapitalMap, where each key represents the name of a country and the corresponding value is the name of its capital city. However, you need to convert this Map to an Object to more easily manipulate and display the data on your website.

Input:

const countryCapitalMap = new Map([
  ['India', 'New Delhi'],
  ['USA', 'Washington D.C.'],
  ['UK', 'London'],
]);  

Solution:

  • We use the spread operator (…) to spread the key-value pairs in the countryCapitalMap into a new array.
  • We then pass this array to the Object.fromEntries() method, which creates a new object with each key-value pair as a property.
  • The resulting object has the same key-value pairs as the original map.
  • Finally, we log the object to the console to verify the conversion.

Solution Code:

// input
const countryCapitalMap = new Map([
  ['India', 'New Delhi'],
  ['USA', 'Washington D.C.'],
  ['UK', 'London'],
]);
//use the spread operator (...) to spread the key-value pairs in the countryCapitalMap into a new 
// array
const countryCapitalObject = Object.fromEntries([...countryCapitalMap]);
console.log(countryCapitalObject);

Output:

{ India: 'New Delhi', USA: 'Washington D.C.', UK: 'London' }

Sample Problem 2: Using the Array.reduce() method

Imagine that you are developing a web application that allows users to rate movies and provides personalised movie recommendations based on their preferences. You have stored each user’s name and age in a Map called myMap, where each key represents the user’s name and the corresponding value is their age.

However, to provide personalized movie recommendations to each user, you need to convert this Map to an Object so that you can easily access and manipulate the user data.

Input:

const myMap = new Map([  ['Alice', 25],
  ['Bob', 30],
  ['Charlie', 35]
]);

Solution:

  • We use the Array.from() method to create an array of the Map entries.
  • We use reduce() method to iterate over arrays and then construct a new object.
  • For each entry, we extract the key and value using destructuring syntax and add them as properties to the new object.
  • Finally, we return the new object.

Solution Code:

// taking input
const myMap = new Map([  ['Alice', 25],
  ['Bob', 30],
  ['Charlie', 35]
]);
function mapToObject2(map) {
// using the reduce() function to iterate the array, then create a new object
  return Array.from(map).reduce((obj, [key, value]) => {
    obj[key] = value;
    return obj;
  }, {});
}

const myObject = mapToObject2(myMap);
console.log(myObject);

Output:

{ Alice: 25, Bob: 30, Charlie: 35 }

Sample Problem 3: Using a loop

Suppose you are working as a developer in a company where your human resource manager tells you that they need to keep track of employee salaries. You have the salary information in a Map object, where the employee ID is the key, and the corresponding value is the salary. However, the system you are using requires the salary information to be in the form of an object with the employee ID as a property and the salary as its value.

Input:

let employees = new Map([
  ['001', 50000],
  ['002', 60000],
  ['003', 70000],
]);

Solution:

  • We define a function called mapToObject that takes a Map as an argument.
  • We initialise an empty object obj.
  • Then to iterate over the pairs of key-values of the Map, we use a for loop.
  • For each pair having key-value, we then add a property to the object with the key and value.
  • Finally, we return the object.

Solution Code:

// input
let employees = new Map([
  ['001', 50000],
  ['002', 60000],
  ['003', 70000],
]);
function mapToObject(map) {
  let obj = {};
  for (let [key, value] of map) {
  // add a property to the object for each key-value pair
    obj[key] = value;
  }
  return obj;
}

let employeeObj = mapToObject(employees);
console.log(employeeObj)

Output:

{ '001': 50000, '002': 60000, '003': 70000 }

Conclusion on how to change map to object in javascript

In this tutorial, we have learned three different approaches to convert a Map to an Object in JavaScript. These approaches are using the spread operator, using the Array.reduce() method, and using a loop.

Every approach has its own pros and cons, so the best suitable approach for a scenario depends on elements like performance, readability, and personal preference.

However, utilising the spread operator approach is the simplest and most concise, and hence it is the recommended approach in most cases.

By choosing the right technique, you can assert that your code is efficient, maintainable, and effective.