Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use a object literal as a hash table?

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?

like image 921
Bradley Morris Avatar asked Nov 21 '17 20:11

Bradley Morris


People also ask

Is object a hash table?

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.

Are hashes the same as objects?

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.

Are Hashtables faster than arrays?

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.

What is the difference between an object and an object literal?

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.


1 Answers

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"));
like image 68
Ori Drori Avatar answered Sep 21 '22 17:09

Ori Drori