I originally flagged this question as a possible duplicate, but having thought about it a bit more I think there's enough differences between the plain Javascript and TypeScript that it is a standalone question ... my bad!
When the JSON is deserialized, it results in a plain object.
Map
is a specific class, and you can't just cast a plain object in to a Map
object.
The documentation for Map
says that it's constructor takes:
An Array or other iterable object whose elements are key-value pairs. Each key-value pair is added to the new Map; null values are treated as undefined.
Unfortunately plain objects are not iterable, so we can't just pass the object to Map's
constructor.
What we can do is loop over the properties, check if they're strings, and then add them to the map.
let objectStringPropertiesToMap = (obj: Object) => {
let map = new Map();
for (let key in obj) {
let val = obj[key];
if (typeof val == "string")
map.set(key, val);
}
};
Which would give you code something like this:
let obj = {
"peureo" : "dsdlsdksd"
};
let objectStringPropertiesToMap = (obj: Object) => {
let map = new Map();
for (let key in obj) {
let val = obj[key];
if (typeof val == "string")
map.set(key, val);
}
return map;
};
let map = objectStringPropertiesToMap(obj);
document.getElementById("output").innerHTML = map.get("peureo");
Which can be seen working on jsFiddle.