...
/Tip 10: Use Objects for Static Key-Value Lookups
Tip 10: Use Objects for Static Key-Value Lookups
In this tip, you’ll learn why objects are the best collection for simple key-value lookups.
When to use a key-value collection?
You probably noticed that I love arrays. But they are not appropriate in many situations. As you saw, it is always possible to store any type of information in arrays—they are really are that flexible—but it can make things more confusing than necessary. And you often end up obscuring information more than you communicate it.
What if you had some data and you wanted to conditionally apply some colors
in the UI. You want the data to be red
if data was below the threshold, green
if
everything is within normal range, and blue
if some data was above a
threshold. As usual, some very smart designers with a lot of training picked
the absolute perfect shades of these colors (personally, I can never tell the
difference, but that’s why I don’t design).
You could put the hex values in an array, but that doesn’t really communicate much.
const colors = ['#d10202', '#19d836', '#0e33d8'];
What the heck does #d10202
even mean? It happens to be a shade of red, but
there’s no way to know that without actually knowing it ahead of time. The
problem is that this data is related—it’s all colors—but not interchangeable.
Unlike an array of users where all users are structurally similar and one can
be substituted for another, the different colors will serve different purposes
(indicating value to users). When a developer wants the ...