How to Create Associative Arrays in JavaScript
-
Create an Associative Array in JavaScript Using the
Map
Object - Create an Associative Array in JavaScript Using Generic Objects
Most programming languages have a data structure that allows you to store data in a key-value format. For example, Python has dictionaries that allow you to associate a string with a value or a list of values.
JavaScript has the Map
object that achieves the same thing, also keep in mind that this functionality is not compatible with older browsers. Historically, simple objects have been used to create associative arrays in JavaScript because they technically do the same thing.
On the other hand, using generic objects for this purpose can get pretty confusing at times. Even the Map
method has its problems, especially if you are new to the language and used to certain conventions.
Create an Associative Array in JavaScript Using the Map
Object
The first and most correct way to handle associative arrays in JavaScript is to create a Map
object. This method has several advantages over regular objects, such as the fact that keys are not limited to strings - they can be functions, other objects, and pretty much any other primitive.
Additionally, Map
objects are also iterable from the get-go. Granted, you can iterate over an object’s properties using a for in
loop, but that is not always an elegant solution.
As such, here is how you can create and populate an associative array in JavaScript:
const myMap = new Map();
myMap.set('firstItem', 1);
myMap.set('secondItem', 2);
myMap.set('thirdItem', 'third');
console.log([...myMap]);
Output:
[["firstItem", 1], ["secondItem", 2], ["thirdItem", "third"]]
To create key/value entries, you can use the set()
method. As a side note, the [...myMap]
syntax used in the code above works because Map
implements an @@iterator
method under the hood. It’s what sets it apart from regular objects since you must create an explicit for in
loop.
If you like to retrieve a specific value, you can use the get()
method:
const myMap = new Map();
myMap.set('firstItem', 1);
myMap.set('secondItem', 2);
myMap.set('thirdItem', 'third');
console.log(myMap.get('firstItem'));
Output:
1
Other useful methods include has()
, which checks if your Map
object has a specific key, and delete()
, which allows you to remove keys from the object.
Avoid Using the Bracket Notation When Dealing With Map
Objects in JavaScript
We all know that JavaScript is full of weird behaviors, and Map
objects are no different, unfortunately.
If you have some background in Python, you might be tempted to use something like myMap["firstItem"] = 1
to set a Map
key/value pair. It’s also a valid approach when dealing with generic objects.
The good news is that this won’t cause any errors, and it will seem to work as intended at first. Here is the above example refactored using the bracket notation:
const myMap = new Map();
myMap['firstItem'] = 1;
myMap['secondItem'] = 2;
myMap['thirdItem'] = 'third';
console.log(myMap);
Output:
[object Map] {
firstItem: 1,
secondItem: 2,
thirdItem: "third"
}
The bad news is that this is no longer the same type of data structure. Instead, this has been transformed into a generic object. Because of this, if you iterate over the Map, it won’t work anymore.
Additionally, the has()
method won’t return the desired results either, as you can see in the code below:
const myMap = new Map();
myMap['firstItem'] = 1;
myMap['secondItem'] = 2;
myMap['thirdItem'] = 'third';
console.log(myMap.has('firstItem'));
Output:
false
In conclusion, you should avoid using the bracket notation when dealing with Map
; otherwise, your code might not work as intended.
Create an Associative Array in JavaScript Using Generic Objects
Until a few years ago, the Map
method described above was not compatible with most browsers, so programmers used generic objects instead. In theory, there’s nothing wrong with this approach, but you should try to use Map
in most cases if backward compatibility is not an issue.
Here is how you can create an associative array in JavaScript using objects:
const myMap = {};
myMap.firstItem = 1;
myMap.secondItem = 2;
myMap.thirdItem = 'third';
console.log(myMap);
Output:
{ firstItem: 1, secondItem: 2, thirdItem: "third"}
Here we used the dot notation to add properties to our object. If you like to use strings as keys, this method will not work as intended if your strings contain spaces.
For those cases, you can use the bracket method as detailed below:
const myMap = {};
myMap['first item'] = 1;
myMap['second item'] = 2;
myMap['third item'] = 'third';
console.log(myMap);
Output:
{ first item: 1, second item: 2, third item: "third"}
JavaScript accepts both methods can again be extremely confusing in some cases. If you truly want to use strings as keys in your associative arrays, then the bracket notation is the way to go since the dot notation is highly restrictive.
On the other hand, the bracket notation makes JavaScript objects look a lot more like classic dictionaries, which they are not. Thus, it is always a much better idea to use the Map
method whenever you have the chance.