How to convert an object into a map - JavaScript

Mo Ibra

Mo Ibra

Dec 20, 2022

In this article we will learn how to convert an object into a map.

It is very common to convert an object into a map in JavaScript.


Problem

Now we have a problem, which is that we want to convert the object into a map

Imagine we have an object like this:

const myObject = {
    name: "John",
    age: 30,
    isMarried: true,
}

console.log(myObject);

// { name: 'John', age: 30, isMarried: true }

And we want to convert this object into a map.

How to solve this problem?

Well, it's easy. We'll create a new map and put the object in it.

But first we should convert object to an array of key-value pairs using Object.entries()


Convert object into a map

As we said before, we will convert our object to an array of key-value pairs using Object.entries()

const myObject = {
    name: "John",
    age: 30,
    isMarried: true,
}

const toArr = Object.entries(myObject);

console.log(toArr);
// [ [ 'name', 'John' ], [ 'age', 30 ], [ 'isMarried', true ] ]

Then we will pass the result to the Map() constructor to create a new Map object:

// Object
const myObject = {
    name: "John",
    age: 30,
    isMarried: true,
}

// Convert to an array
const toArr = Object.entries(myObject);

// Convert to map
const result = new Map(toArr);

// Result:
console.log(result);

Output

Map(3) { 'name' => 'John', 'age' => 30, 'isMarried' => true }

Yay 🚀🚀


But what will happen if we put the object directly in the map while we are creating it?

// Object
const myObject = {
    name: "John",
    age: 30,
    isMarried: true,
}

// Error:
const result = new Map(myObject);

// Result:
console.log(result);

Output

object is not iterable (cannot read property Symbol(Symbol.iterator))

This will cause a problem as you can see, because it is an expected iterable object.


Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: