Explain Codes LogoExplain Codes Logo

How to create a dictionary and add key value pairs dynamically in JavaScript

javascript
dictionary
dynamic-keys
object-methods
Alex KataevbyAlex Kataev·Aug 5, 2024
TLDR

Here's the quick and simple recipe for cooking up a JavaScript object used as a dictionary:

let dict = {}; // Start fresh. Empty dictionary. dict['specialKey'] = 'megaValue'; // Spice it up with bracket notation // Or, if your key is dieting (aka valid identifier): dict.lightKey = 'lightValue'; // Dot notation, please! console.log(dict); // Pickup! order is ready: { specialKey: 'megaValue', lightKey: 'lightValue' }

Juggling dynamic key names when they've got "personality" (non-valid identifiers or runtime generation)? You're gonna want to stick with bracket notation to prevent spillage.

Working with Escaped Keys

Sometimes, you're handling keys that are acting all strange at runtime, or those that have decided identifier status just isn’t for them (think spaces or hyphens). For these misfits, go for bracket notation:

let keyName = 'Fancy Key ' + Date.now(); // Dynamic key, feeling fancy. dict[keyName] = 'secretValue'; console.log(dict[keyName]); // And... it worked!

Dictionary Crash Course: Safety First!

Always, and I repeat, always check if a key exists before you begin your magic to prevent nasty runtime errors from crashing your party:

if (dict.hasOwnProperty('mustHaveKey')) { console.log('Ready to rock! The value is:', dict['mustHaveKey']); } else { console.log('Oops! This key is MIA.'); }

The delete keyword - it's like telling a key it's "Fired!" from the dictionary –use with caution.

The Never Ending Construction Site

Your dictionary is your project, it grows with every new iteration like in a loop or every new piece of input from your end users:

for (let i = 0; i < randomKeys.length; i++) { dict[randomKeys[i]] = randomValues[i]; // Every loop, a key-value pair is born. Isn't it beautiful? }

And when we talk user input:

function hearTheUser(key, value) { dict[key] = value; // Voila! Your wish is my command. }

Helper Objects to The Rescue!

Some situations call for the power of Object methods. Superheroes like Object.keys(), Object.values(), and Object.entries() can be real lifesavers when you're in the thick of things:

for (let key of Object.keys(dict)) { console.log(key, dict[key]); // You get a key! You get a value! Everyone gets a key-value! }

When things get complicated, these guys can clone or merge dictionaries faster than you can say "Supercalifragilisticexpialidocious".

Keys Flaunting All Shapes & Sizes

Squared brackets let your keys bloom however they fancy. Need non-identifier strings or numeric keys? Make it happen:

dict['404Error'] = 'Not Found'; // Nothing to see here dict[123] = 'Numeric key'; // Hey it's me, your number pal.