Skip to content

Convert map to object JavaScript

  • by

In JavaScript, you can convert a Map to an Object using the Object.fromEntries() method. This method takes an array of key-value pairs and returns an object with the keys and values from the array.

The resulting object will have string keys, even if the original map had non-string keys, and it will only include the last occurrence of each key.

const myMap = new Map();
// add some key-value pairs to myMap

const myObject = Object.fromEntries(myMap);

Convert the map to object JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
<body>
    <script>
       const myMap = new Map([
            ['key1', 'value1'],
            ['key2', 'value2'],
            ['key3', 'value3']
        ]);

        const myObject = Object.fromEntries(myMap);

        console.log(myObject);

    </script>
</body>
</html>

Output:

Convert map to object JavaScript

Another method use the spread operator and the Object.assign() method.

// Create a Map object
const myMap = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

// Convert Map to Object
const myObj = Object.assign({}, ...myMap.entries());

console.log(myObj); // Output: {key1: "value1", key2: "value2", key3: "value3"}

Or use the forEach() method

// Convert Map to Object using forEach
const myObj = {};
myMap.forEach((value, key) => {
  myObj[key] = value;
});

Or use the for...of loop

// Convert Map to Object using for...of loop
const myObj = {};
for (const [key, value] of myMap) {
  myObj[key] = value;
}

Do comment if you have any doubts or suggestions for this JS Converting map topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading