How to Convert Map to JSON in JavaScript

Migel Hewage Nimesha Feb 02, 2024
  1. the map() Function in JavaScript
  2. Use a Map in JavaScript
  3. Use the JSON.stringify() Method in Map to JSON
  4. Use the object.fromEntries() Method in Map to JSON
  5. Convert a Map to JSON String
  6. Conclusion
How to Convert Map to JSON in JavaScript

JavaScript Object Notation (JSON) is a text-based format for commonly presenting structured data. In JavaScript, we can simplify our code by using the map() function.

the map() Function in JavaScript

A collection of key/value pairs known as a map() can use any data and recalls the order in which it inserts.

Such a great new syntax is a map(). It is an excellent tool for changing every element in a JavaScript array.

It uses to loop through all the arrays. Depending on the outcomes, it may create from recently finished elements or modify elements of an array to form a new range.

The keys in anything can be a map(), including arrays, objects, and integers.

Below the example, the firstName and middleName values can be combined using the map() method to loop through the array.

let users = [
  {firstName: 'Bob', middleName: 'Mel', lastName: 'Lee'},
  {firstName: 'Joanna', middleName: 'Kaccy', lastName: 'Smith'},
  {firstName: 'Peter', middleName: 'Jone', lastName: 'Steward'}
];

let Fullnames = users.map(function(element) {
  return `${element.firstName} ${element.middleName} ${element.lastName}`;
})

console.log(Fullnames);

Here’s the output of the above code:

map example

Using the map(), you can add or delete new and existing interfaces and retrieve their value. The syntax of the map method is below.

arr.map(function(element, index, array) {}, this);

Each element of the array calls the callback function, which always passes the current element, the current element’s index, and the entire array object.

Use a Map in JavaScript

You can use a map to collect and add the outputs to a new array. A similar task can achieve using either a for loop or “nesting” in JavaScript.

But we can create functions that are simpler to read by using a map() function.

With the new map() syntax, the map() may be built, initialized, and then values can be added.

We can create a new map(), called the firstMap.

let firstMap = new Map()

The output will be an empty map.

new map

If you want to give some value to a map() function, you should create a Map object by using a new Map().

For example, use the new map favCharacter to create a map object. Below is a discussion on it.

let favCharacter = new Map([
  ['Brett Lee', 'Australian'], ['Muttiah Muralitharan', 'SriLankan'],
  ['Chris Gayle', 'West Indian'], ['Wasim Akram', 'Pakistan']
]);
console.log(favCharacter);

Here’s the output of the above code:

new map object

Stores with world-famous cricketers’ names and nationalities on that map objects in this example. We can get an output similar to that shown above by using console.log(favCharacter);.

Use the JSON.stringify() Method in Map to JSON

First, we can create a map() with keys and values as strings. The Map.forEach method uses it to run through the map, which includes a call for every element.

After that, an object creates and adds the keys and values. Lastly, the object returns the JSON.stringify() method in JSON format.

let detail = new Map()
detail.set('Name', 'Lora');
detail.set('Country', 'England');
detail.set('Age', '24');
let jsonObject = {};
detail.forEach((value, key) => {jsonObject[key] = value});
console.log(JSON.stringify(jsonObject))

Here’s the output of the above code:

stringify

Use the object.fromEntries() Method in Map to JSON

The Object.fromEntries() method uses to get the input map and convert it into a JSON object of keys and values. fromEntries method in an object class was introduced in ES6.

Below, we can see an example of this method.

let detail = new Map()
detail.set('Name', 'Lora');
detail.set('Country', 'England');
detail.set('Age', '24');
const result = Object.fromEntries(detail);
console.log(result)

Here’s the output of the above code:

fromEntries

Convert a Map to JSON String

Likewise, we can use Object.fromEntries() to turn a map into a JSON string and a JavaScript object. Then pass that object as an argument to the JavaScript method JSON.stringify().

Syntax:

var obj = Object.fromEntries(details);
var jsonString = JSON.stringify(obj);

We can convert a JavaScript map to a JSON string using this syntax. You can see how that syntax works in the example below.

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var detail = new Map([['Name', 'James'],['Country', 'America'],['Age', 23]]);
        var obj = Object.fromEntries(detail);
        var jsonString = JSON.stringify(obj);
        document.getElementById('output').innerHTML += jsonString;
    </script>
</body>
</html>

Here’s the output of the above code:

map to json string

Conclusion

This article looked at how to convert a JavaScript map to JSON. We have discussed several methods that can be used.

Mainly, we learned how to use JavaScript’s JSON.stringify() method and Object.fromEntries() method to transform a map into a JSON string.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - JavaScript Map