Browse the notebook

Tag: Dictionary

Dictionary with ES6 Symbol

Creating a dictionary type object with ES6 Symbols is easy. Yes we have Maps and WeakMaps but this is still interesting for a variety of reasons… Being able to use objects as keys in another object (dictionary) has many great uses…. So how do you use Symbols like this?

let a = { id: Symbol('key') },
    b = { id: Symbol('key') };

let dictionary = {
  [a.id]: 'value by obj a',
  [b.id]: 'value by obj b'
};

console.log(dictionary[a.id]);
console.log(dictionary[b.id]);

// outputs:
// 'value by obj a'
// 'value by obj b'

By using either object a or object b’s `id` symbol, our dictionary points to another value. This old AS3 snippet is similar:

https://actionsnippet.com/?p=426

Read snippet: Dictionary with ES6 Symbol