Convert Map to Object

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert a Map to an object in JavaScript. We will use the Map.prototype.entries() method to get an array of key-value pairs from the Map and then use Object.fromEntries() to convert the array to an object. This lab will provide a better understanding of the use of Map and Object in JavaScript.

Instructions for Converting Map to Object in JavaScript

To convert a JavaScript Map to an object, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Map.prototype.entries() method to convert the Map to an array of key-value pairs.
  3. Use the Object.fromEntries() method to convert the array to an object.

Here is an example code snippet for converting a Map to an object:

const mapToObject = (map) => Object.fromEntries(map.entries());

To test the function, you can run:

mapToObject(
  new Map([
    ["a", 1],
    ["b", 2]
  ])
); // {a: 1, b: 2}

Summary

Congratulations! You have completed the Convert Map to Object lab. You can practice more labs in LabEx to improve your skills.