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

Is it good to use an object literal as a hash table? use the property name as the key to return the specific display value.

For instance:

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 template that handles the hash map better in JavaScript?

+4
source share
1 answer

Before ES6 using literal was the only way to have a hash map in JS. Starting with 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 console

console.log(map.get("#4286f4"));
Run code
+7
source

Source: https://habr.com/ru/post/1689648/


All Articles