Explain Codes LogoExplain Codes Logo

How to do associative array/hashing in JavaScript

javascript
associative-array
map
json
Anton ShumikhinbyAnton Shumikhin·Aug 18, 2024
TLDR

For basic associative arrays, use JavaScript Objects with string keys:

let fruitHash = { 'apple': 1, 'banana': 2 }; fruitHash['cherry'] = 3; // adding to the "fruit salad" console.log(fruitHash['apple']); // Who ate my apple? ;)

If you need advanced functionality, like non-string keys or performance optimization, prefer Maps:

let fruitMap = new Map([['apple', 1], ['banana', 2]]); fruitMap.set('cherry', 3); // Map knows, pineapple goes on pizza console.log(fruitMap.get('apple')); // Still looking for my apple...

Use Objects for simpler cases. Consider Maps when keys are non-strings or if you're dealing with large datasets.

Getting more mileage: beyond basics

Accessing object properties

You can manipulate properties of objects using dot notation or bracket notation. Use bracket notation for keys containing special characters.

let obj = { 'one-two': 12, 'three four': 34 }; console.log(obj['one-two']); // Enough math for today, thanks.

Traversing associative arrays

Use a for..in loop to traverse through keys in an object. With a pinch of hasOwnProperty, you can filter out any inherited properties.

for (let fruit in fruitHash) { if (fruitHash.hasOwnProperty(fruit)) { console.log(fruit + " -> " + fruitHash[fruit]); // rolling in the deep (fruit salad) } }

Boosting performance with Map objects

Map objects are faster than objects for large data sets and offer constant-time complexity for look-ups, no matter the size of your data.

Covering all bases: dealing with edge cases

Non-string keys? Not a problem

Use the Map object for non-string keys. Unlike objects which convert keys to strings, Map preserves their type.

Clean up with WeakMap

Consider using WeakMap for scenarios where auto garbage collection is needed. Keys are objects, and when there are no more references to them, they are automatically garbage collected.

The good old Dictionary vibes

For those coming from C# or similar backgrounds, you may feel homesick for the Dictionary structure. While JavaScript Objects or Maps aren't exactly identical, they do a pretty good job mimicking it.

Important! Serialization and deserialization

JSON for the data interchange crown

Need to exchange data between the client and server? Say hello to JSON (JavaScript Object Notation). Coping with JSON in JavaScript is as easy as JSON.stringify and JSON.parse.

Keeping track of Maps

Persistent storage or serialization of a Map? We traverse manually and form an array or object structure.

let serializedMap = JSON.stringify(Array.from(fruitMap.entries())); // Mapping the way for persistent storage // Persist JSON or toss it across the network

To rehydrate:

let deserializedMap = new Map(JSON.parse(serializedMap)); // Resurrecting our Map from the JSON crypt.

Keep in mind

  • Objects for string keys and static keys.
  • Maps perfect for large datasets, dynamic keys or frequent additions/removals.
  • Use WeakMaps for auto garbage collection where keys are objects.