Initially, I marked this question as a potential duplicate. However, upon further consideration, I realized that there are significant differences between plain JavaScript and TypeScript, making it a unique question ... my mistake!
After deserialization, the JSON results in a plain object.
Map
is a distinct class, and converting a plain object into a Map
object is not straightforward.
The Map
documentation specifies that its constructor accepts:
An Array or other iterable object containing key-value pairs. Each pair is added to the new Map; null values are treated as undefined.
Unfortunately, plain objects do not support iteration, preventing direct conversion to a Map
.
One approach is to iterate over the properties, validate if they are strings, and then insert them into the map.
let convertObjectToStringPropertiesToMap = (obj: Object) => {
let map = new Map();
for (let key in obj) {
let val = obj[key];
if (typeof val == "string")
map.set(key, val);
}
};
This would result in code similar to the following:
let obj = {
"example" : "sample"
};
let convertObjectToStringPropertiesToMap = (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 = convertObjectToStringPropertiesToMap(obj);
document.getElementById("output").innerHTML = map.get("example");
You can see this in action on jsFiddle.