Henrik Clausen
Henrik Clausen

Reputation: 729

Add items to array in typescript map

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?

Upvotes: 1

Views: 7443

Answers (1)

axiac
axiac

Reputation: 72186

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');

Upvotes: 5

Related Questions