1

I have a JS Map that looks like this let mappy = new Map<string, string[]>() I would like to add items to the array using the key and I could do this:

mappy.set(theKey, mappy.get(theKey).push('somevalue'));

that just seems like overkill to me. if I used a simple object I could easily just do

let mappy = {};
mappy[theKey] = [];

..and then later mappy[theKey].push('somevalue') but this kinda negates the typed object idea of TS

Is there any way i could add to that array in the map without first "getting" it?

1
  • Why .set() anything? You just need to .get() the array and .push() to it. In fact .push() returns a number - the new length of the array. So if you .set(someKey, someArray.push()) you're setting the value of someKey to a number. Commented May 8, 2021 at 14:40

1 Answer 1

5

You can get a reference to the array from the Map object and push extra values to it. There is no need to put it back in the Map, it already is there.

mappy.get(theKey)!.push('somevalue');

The ! after mappy.get(theKey) is needed because TypeScript complains that the value returned by mappy.get() can be undefined. The exclamation mark tells it that we know for sure that the value is defined. It is called a "definite assigment assertion" and has been introduced in TypeScript 2.7.

Check it online.


Or you can also use a plain object instead of a Map:

type MyMap = { [K: string]: string[] };
let mappy: MyMap = {};

mappy[theKey] = [];
mappy[theKey].push('somevalue');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man.. I learned 3 new things from that post.. Its a good day!!!

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.