To convert a JSON string to a map in TypeScript, you can use the JSON.parse method to parse the JSON string into an object and then convert the object into a Map.
We can convert a JSON string to a map in TypeScript by using the JSON.parse method to parse the JSON string into an object and then converting the object into a Map.
For example,
JSON.parse
method to parse the JSON string into an object.Map
by passing the object's entries (key-value pairs) to the Map constructor.const jsonString = '{"1": 10, "2": 20, "3": 30, "4": 40, "5": 50}';
// Parse the JSON string into an object
const jsonObject = JSON.parse(jsonString);
// Create a new Map from the object's entries
const myMap = new Map<string, number>(Object.entries(jsonObject).map(([key, value]) => [key, Number(value)]));
// Print the resulting map
console.log('Map from JSON string:');
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Map from JSON string: 1: 10 2: 20 3: 30 4: 40 5: 50
In this tutorial, we learned How to Convert a JSON String to a Map in TypeScript language with well detailed examples.