4

I have a class in Typescript containing a map:

public map:Map<string,string>;
constructor() {
  let jsonString = {
    "peureo" : "dsdlsdksd"
  };
  this.map = jsonString;
}

Problem is that the initialization doesn't work.

jsonString is something that I will receive from a Java Object serialized to Json.

Anyone can help? Thanks!

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
Laurent T
  • 1,070
  • 4
  • 13
  • 25
  • @MarkRotteveel I assume because the object is serialized in a Java app. " jsonString is something that I will receive from a Java Object serialized to Json" But you're right that that's an irreverent detail. –  Jul 20 '17 at 15:41

2 Answers2

7

You must iterate over the members of the object and add it to the map:

public map: Map<string, string> = new Map<string, string>();

constructor() {
    let jsonString = {
        "peureo": "dsdlsdksd"
    };

    for (let member in jsonString) {
        this.map.set(member, jsonString[member]);
    }
}
1

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.