{

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.

How to Convert Map to JSON object examples

There are multiple ways we can do this.

parse Map into JSON object using Iterate and 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 Map.
  • Object created and added keys and values.
  • Finally, Object is returned in JSON format using 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"}

use ES6 Object fromEntries method

ES6 introduced fromEntries method in an object class. fromEntries takes 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"
}

How to Convert JSON object to Map with examples

Following are ways to convert JSOn to Map Object

using for in loop iteration

Created JSON Object which contains key and values Next created Empty map used for…in loop to iterate the JSON object and added key and values to 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);  

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.