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

In JavaScript, the 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, 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 function to create our new array of objects:

let colorsWithHex = => {
    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:


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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s