How can I create a Map with non-unique keys in JavaScript/TypeScript?

1440 views javascript
-2

To interface with existing code, I am hoping to implement a Map with non-unique keys in JavaScript/TypeScript (for a web app in Angular).

I know that Maps in JavaScript/TypeScript enforce unique keys. How can I implement a "non-unique" Map?

Creating an array of Key-Value objects does not work as the structure does not de-serialize from JSON in the correct shape for the existing consumer code.

For example, I am hoping to create something like the following structure:

vehicleOptions : NonUniqueMap<key: string, value: {color: string, isTowingCapable: boolean}>
{
  "Truck", { "Red", true },
  "Compact Sedan", { "Black", false },
  "Compact Sedan", { "Blue", false }
}

answered question

Use an array instead, which contains objects, eg { label: 'Truck', obj: { ... } }. Note that your current { "Red", true } is invalid syntax, key-value pairs need to be separated by colons, not commas

why don't use Array instead ?

It's not clear how you would use this data structure. For example, why do you expect to get back when you use the key Compact Sedan on your object?

1 Answer

12

You can't.

You can create a unique map. When you have two same keys, you can store it as:

const map = {
    "Truck": [{ "Red": true }],
    "Compact Sedan": [{ "Black": false }, { "Blue": false }]
}

Then, when you get the value of Compact Sedan, you get an array.

So you can get the first/second value:

map["Compact Sedan"][0]; // { "Black": false }
map["Compact Sedan"][1]; // { "Blue": false }

posted this

Have an answer?

JD

Please login first before posting an answer.