How To Convert Object To Map In JavaScript

In JavaScript, we often need to convert objects into Maps. A map is a data structure that allows us to save the data in pairs of key-values.

Map is commonly used in situations where you need to perform quick lookups or keep your keys in a specific order. This makes it a useful tool for organising and managing data efficiently.

In JavaScript, objects and maps are two different data structures with different methods and features. Objects are used to store pairs of key-value, just like maps but maps are designed specifically for this purpose, and they also offer a few advantages over objects.

This tutorial will look at some approaches for converting an object to Map in JavaScript.

Need for converting Object to map in JavaScript

Converting an object to a Map can be useful in the following scenarios:

  • Faster lookups: When we need to perform fast lookups based on a key.
  • Orderly iteration: Converting Object to map is useful for situations where you need to preserve the order of keys and values, such as iterating over them in a specific order.
  • Store all types of values: It is also useful when we need to store values that may not be valid keys in an object.
  • Convenient: Maps have built-in methods for working with keys and values, such as set(), get(), and has(), whereas objects do not.

Different Approaches on converting object to map in javascript

There are several approaches on how to change object to Map in JavaScript:

  1. Using the Map constructor
  2. Using a for…of loop
  3. Using the spread operator

Approach 1: Using the Map constructor

This approach involves using the Map constructor and the Object.entries() method to convert an object to a Map. After accepting  an object as input, this method generates an array, which then is used to create a new Map object.

The resulting map object is a Map with the same key-value pairs as the object.

Here’s an example:

Sample Code:

const obj = { a: 1, b: 2, c: 3 };      // input

 // using the Object.entries() method to convert the object to an array of key-value pairs
const map = new Map(Object.entries(obj)); 

console.log(map);

Output:

Map { 'a' => 1, 'b' => 2, 'c' => 3 }

Code Explanation:

  • We declare an object obj with key-value pairs.
  • We use the Object.entries() method to change the object to an array of pairs of key-value pairs.
  • We pass this array to the Map constructor, which actually creates a new Map with key-value pairs.
  • We log the resulting Map to the console.

Approach 2: Using a for…of loop

This approach involves using a for…of loop to iterate over the keys of objects using the Object.keys() method, i.e. for each key, we use Map.prototype.set() method to add the key-value pair to the map.

The resulting map object is a Map with the same key-value pairs as the object.

Sample Code:

const obj = { a: 1, b: 2, c: 3 };       // input

const map = new Map();

for (let [key, value] of Object.entries(obj)) {
  map.set(key, value);     //adding each key-value pair using the Map.prototype.set() method
}

console.log(map);

Output:

Map { 'a' => 1, 'b' => 2, 'c' => 3 }

Code Explanation:

  • We declare an object obj with key-value pairs.
  • We create an empty Map using the Map constructor.
  • We use a for…of loop to iterate over the key-value pairs in the object.
  • We add each key-value pair to the Map using the Map.prototype.set() method.
  • We log the resulting Map to the console.

Approach 3: Using the spread operator

This approach involves using the spread operator (…) to convert an object to a Map. The spread operator is used to expand the properties of an object into individual elements, which can then be added to a new Map object.

This approach can be used on any object that has enumerable properties, including arrays.

Sample Code:

// Create an object with three properties
const obj = { a: 1, b: 2, c: 3 };

// Create a new Map object using the spread operator and Object.entries()
const map = new Map([...Object.entries(obj)]);

// Log the Map object to the console to verify it has been created correctly
console.log(map);

Output:

Map { 'a' => 1, 'b' => 2, 'c' => 3 }

Code Explanation:

  • We create an object with three properties – a, b, c.
  • Next, we create a new Map object using the spread operator (…).
  • We pass the result of calling Object.entries() with the object as an argument to the Map constructor. The Object.entries() method returns an array of pairs of key-value pairs for each property in the object.
  • The spread operator is used to expand the array returned by Object.entries() into individual key-value pairs.
  • The resulting key-value pairs are added to the new Map object.
  • Finally, we log the Map object to the console to verify that it has been created correctly.

Best Approach for “how to convert object to map in JavaScript”

The best approach when dealing with the conversion of object to Map in JavaScript is to use the map constructor for the following reasons:

  • Simple and easy to understand: It requires only a single line of code which makes it very efficient in converting object to Map
  • Versatile: This method is capable of handling nested objects as well, making it a versatile option for converting objects to Map objects.
  • Handling nested objects: It recursively converts nested objects into Map objects, which can then be added to the main Map object.

Sample Problems on how to change object to map in javascript

Sample Problem 1: Using the Map constructor

You are working for an ecommerce website – Mintraa. The website sells various products such as T-shirts, shoes, jeans etc.

Imagine you have been given the task of writing a code solution that will take an object of products with their respective properties, such as name, price, and colour, and change it into Map object.

Input: 

const views = {
  "Product A": 100,
  "Product B": 200,
  "Product C": 150,
  "Product D": 50
};

Solution:

  • We have an object view that contains the view count for each product.
  • We create a new Map object using the Map constructor and passing the result of calling Object.entries(views) as an argument.
  • The Object.entries(views) method returns an array of key-value pairs for each property in the views object.
  • The spread operator is used to expand the array returned by Object.entries() into individual key-value pairs.
  • The resulting key-value pairs are added to the new Map object.
  • Finally, we log the Map object to the console to verify that it has been created correctly.

Solution Code:

// taking object as input
const views = {
  "Product A": 100,
  "Product B": 200,
  "Product C": 150,
  "Product D": 50
};
// creating a new Map object using the Map constructor and passing the result of calling Object.entries(views) as an argument
const map = new Map(Object.entries(views));

console.log(map);

Output:

Map(4) {
  'Product A' => 100,
  'Product B' => 200,
  'Product C' => 150,
  'Product D' => 50
}

Sample Problem 2: Using a for…of loop

Suppose you are creating a website where you need to store the details of different users in a JavaScript object. However, you need to convert this object into a Map object to display the data in a particular order. You want to use the for…of loop and the Map.prototype.set() method to achieve this. You have to come up with a code solution to change objects to map in javascript.

Input:

const users = {
  user1: {
    name: "John",
    age: 30,
    email: "[email protected]"
  },
  user2: {
    name: "Jane",
    age: 25,
    email: "[email protected]"
  },
  user3: {
    name: "David",
    age: 40,
    email: "[email protected]"
  }
};

Solution:

  • Initialise an empty Map object.
  • Use a for…of loop to loop through the object.
  • Use Object.entries() method to change the object into an array of key-value pairs.
  • Destructure the array into key and value variables.
  • Use the set() method of Map object to add key-value pairs into the Map.

Solution Code:

// take input
const users = {
  user1: {
    name: "John",
    age: 30,
    email: "[email protected]"
  },
  user2: {
    name: "Jane",
    age: 25,
    email: "[email protected]"
  },
  user3: {
    name: "David",
    age: 40,
    email: "[email protected]"
  }
};

// initialize an empty Map
const userMap = new Map();

// loop through the object using for...of loop
for (const [key, value] of Object.entries(users)) {
  // set the value in the Map
  userMap.set(key, value);
}
console.log(userMap);

Output:

Map(3) {
  'user1' => { name: 'John', age: 30, email: '[email protected]' },
  'user2' => { name: 'Jane', age: 25, email: '[email protected]' },
  'user3' => { name: 'David', age: 40, email: '[email protected]' }
}

Sample Problem 3: Using the spread operator

Suppose you are working for an e-commerce website – Mintraa. The website sells various products such as T-shirts, shoes, jeans etc. Your task is to write a code that will input an object of products with their respective properties, such as name, price, and color, and transform it into a Map object.

Input:

const products = {
  product1: {
    name: "T-shirt",
    price: 20,
    color: "red"
  },
  product2: {
    name: "Shoes",
    price: 50,
    color: "black"
  },
  product3: {
    name: "Jeans",
    price: 40,
    color: "blue"
  }
};

Solution:

  • Use the Object.entries() method to change the object to a key-value paired array.
  • Use the spread operator to spread the key-value pairs inside the Map constructor.
  • Create a new Map object with the spread key-value pairs.

Solution Code:

// take input
const products = {
  product1: {
    name: "T-shirt",
    price: 20,
    color: "red"
  },
  product2: {
    name: "Shoes",
    price: 50,
    color: "black"
  },
  product3: {
    name: "Jeans",
    price: 40,
    color: "blue"
  }
};
// create a new Map object using the spread operator
const productMap = new Map([...Object.entries(products)]);

console.log(productMap);

Output:

Map(3) {
  'product1' => { name: 'T-shirt', price: 20, color: 'red' },
  'product2' => { name: 'Shoes', price: 50, color: 'black' },
  'product3' => { name: 'Jeans', price: 40, color: 'blue' }
}

Conclusion on how to convert object to map in javascript

In conclusion, converting objects to maps are useful for scenarios where you need to preserve the order of keys and values or when you need to use a non-string data type as a key, such as an object or a number.

Maps can use any data type as a key, including objects, whereas objects can only use strings as keys.

There are three main approaches to convert an object to a Map in JavaScrip. After analysing all the approaches, the best approach for this conversion is using the Map constructor. This is because using the map constructor is the most efficient and straightforward approach requiring only a single line of code, and it also provides an efficient way of handling nested objects.

However, it would be advisable to come up with the best possible approach depending on the specific scenario or the requirements.