2

I must be missing something here. I try to put a value into a map but it doesn't want to work.

const tempMap = new Map();
tempMap.set("bla", "bla");
console.log(tempMap)
--> output: {}

Can someone explain to me why it is like that? Shouldn't the output have the added value in it?

Try it yourself in the playground.

3
  • 2
    The value is added. Try logging Array.from(tempMap.keys()) or Array.from(tempMap.values()) Commented Nov 11, 2020 at 11:23
  • console.log(tmpMap.get("bla")) Commented Nov 11, 2020 at 11:26
  • console.log(tempMap.has("bla")) Commented Nov 11, 2020 at 14:53

2 Answers 2

3

The class itself won't export any values, use should use the API

You want to do something like this:

let tmpMap = new Map();
tmpMap.set("bla", "bla");
console.log(tmpMap.get('bla')); // bla

You can also iterate in tempMap.keys() or tempMap.values() like @Evan already commented.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation :) looks like I've still got some way left with Typescript and how these types really work.
In the end I like to serialize this map to session storage e.g. sessionStorage.setItem("some_key", JSON.stringify(tmpMap));. I could get all the values, but do you have a suggestion on how to serialize the object as a whole?
If you want to use the object itself, maybe Map is not what you looking for. You can create an custom interface and use typescriptlang.org/docs/handbook/…
0

In the end I used the Record type for my purpose. Which is a kind of dictionary type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.