2

I am trying to initialize below Map in typescript. When I print it, it seems to be empty.

let map: Map<string, object> = new Map<string, object> ([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log(JSON.stringify(map));
// printing {}
// but not the initialized values
0

3 Answers 3

1

It is initialized correctly, but printing it does not print all values like an array. But you can check it by just accessing the keys - they exist:

let map = new Map([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log(map);
console.log(map.get('api/service/method'));
console.log(map.get('"type": "html"'));

Also relevant: How can I display a javascript ES6 map object in console?

As stated there you could just spread the map and print that:

let map = new Map([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log([...map]);

0

That's because JSON.stringify doesn't know how to stringify a Map, so it will try to stringify the underlying object instead, which results in an empty object.

Try console.log(JSON.stringify([...a.entries()])); instead

0

Stringifying an object involves stringifying its properties, but a Map doesn't use properties to save its data. Thus you get an empty object if you naively stringify it.

Instead convert it to an array first:

console.log(JSON.stringify([...map]));

Not the answer you're looking for? Browse other questions tagged or ask your own question.