{

Typescript - How to convert Map to/from JSON with examples| Javascript example


typescript encapsulation tutorials with examples

In Typescript applications, We used to get the use cases where data in map object convert to JSON object or JSON to Map conversions.

In this blog, We are going to learn how to convert Map to JSON or JSON to Map.

The map is a data structure introduced in ES6 for storing key and values.

JSON is a javascript object notation for the format of key and values enclosed in braces. This code works in Javascript as this uses the Latest Es6 classes and syntax.

There are multiple ways we can do this.

How to Convert Map into JSON object using typescript Iterate Stringify method

First

  • Map is created with key and values of type strings
  • map.forEach method is used to iterate the map that contains a callback called for every element of the Map.
  • Object created and added keys and values.
  • Finally, the Object is returned in JSON format using the JSON.stringify() method
let map = new Map<string, string>();
map.set("one", "value1");
map.set("two", "value2");
map.set("three", "value3");
let jsonObject = {};
map.forEach((value, key) => {
  jsonObject[key] = value;
});
console.log(JSON.stringify(jsonObject));

Output:

{"one":"value1","two":"value2","three":"value3"}

How to Convert Map into JSON object using typescript ES6 Object fromEntries method

ES6 introduced fromEntries method in an object class. fromEntries takes the input map and convert key and values into a JSON object.

let map = new Map<string, string>();
map.set("one", "value1");
map.set("two", "value2");
map.set("three", "value3");
const result = Object.fromEntries(map);

console.log(result);

Output:

{
  one:"value1",
  two:"value2",
  three:"value3"
}

Following are ways to convert JSOn to Map Object

How to Convert JSON object to Map using Typescript for in-loop iteration

Created JSON Object which contains key and values Next created an Empty map using for…in loop to iterate the JSON object and added keys and values to the Map instance.

let jsonObject = { one: "value1", two: "value2", three: "value3" };
let map = new Map<string, string>();
for (var value in jsonObject) {
  map.set(value, jsonObject[value]);
}
console.log("map:" + map.size);

How to Convert JSON object to Map using Typescript ES6 entries method

Object entries method is introduced in ES6 which converts JSOn object to MAP in javascript and typescript.

let jsonObject = { one: "value1", two: "value2", three: "value3" };
const result = Object.entries(jsonObject);
console.log(result);

Summary

To summarize, We have learned multiple ways to convert JSON objects to/from JSOn in typescript and javascript.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.