To convert a JSON string to a map in JavaScript, 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 JavaScript 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(Object.entries(jsonObject));
// 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 JavaScript language with well detailed examples.