Is it good practice to use a object literal as a hash table? i.e use a property name as the key to get a particular mapped value back.
For example:
var colorArray = [
{ code: "#4286f4", name: "Blue" },
{ code: "#fc4d02", name: "Red" }
]
var hashTable = {}
colorArray.forEach(color => {
hashTable[color.code] = color.name
})
Is this an acceptable use for object literals, or is there a pattern out there that will better handle a hash map in JavaScript?
A JavaScript Object is an example of a Hash Table because data is represented a key/value pairs. A hashing function can be used to map the key to an index by taking an input of any size and returning a hash code identifier of a fixed size.
Often we compare hashes in Ruby to Objects in JavaScript. Although they share some similarities, the functionality of both are not the same. The similarities stem from the fact that Ruby's hash and JavaScript's object appear to look the same. Lets take a look at how each are created with their seemingly similar syntax.
Hash tables tend to be faster when it comes to searching for items. In arrays, you have to loop over all items before you find what you are looking for while in a hash table you go directly to the location of the item. Inserting an item is also faster in Hash tables since you just hash the key and insert it.
Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
Before ES6 using a literal object was the only way to have a hashmap in JS. Since ES6, you can also use Map:
const colorArray = [{code: "#4286f4" , name: "Blue"}, {code: "#fc4d02", name: "Red"}];
const map = new Map(colorArray.map(({ code, name }) => [code, name]));
console.log(map); // look at the browser's console
console.log(map.get("#4286f4"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With