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

Viewed 584

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?

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"));

Related