Using JavaScript map() to Map an Array of Primitives to One of Objects

In JavaScript, the Array.map() method is often used to map a list of objects into a more simple array comprised of the values from particular field in all the objects. The other day, I had a need to expand an array of strings, into an array containing that string and another reference value. It turns out that’s possible using Array.map(), so I thought I’d create a short post illustrating how to do so.

For our example, let’s pretend we’ve got a list of colors that we need to map to their hex codes.

Here’s our array of color names:

let colors = ["red", "orange", "yellow", 
    "green", "blue", "violet"];

Assuming we’ve got a method defined called findHexCode, we can now use the Array.map() function to create our new array of objects:

let colorsWithHex = colors.map(color => {
    return { name : color, hex : findHexCode(color)};
});

In our callback function, we build our object with the color stored in map field and the hex code in the hex field.

Our new colorsWithHex array looks like this:

[{'name':'red','hex':'#FF0000'},{'name':'orange','hex':'#FFA500'},{'name':'yellow','hex':'#FFFF00'},
{'name':'green','hex':'#008000'},{'name':'blue','hex':'#0000FF'},{'name':'violet','hex':'#EE82EE'}]

That’s all there is to it and we could probably get even fancier if we wanted to. The full example is available in this CodePen.

Advertisement