A ferris wheel photographed against a bright blue sky

Ordinary arrays can be looped through using a standard for, but JSON objects are special, since each “slot” contains an information pair: a property, and a value for that property. To extract those pieces and address them separately often requires a different approach, one of which is the for…in loop.

A good example of this is the named CSS colors object I created for my recent article on the same. The JSON array starts like this:

var cssColors = {  
  "aliceblue": "#f0f8ff",
  "antiquewhite": "#faebd7",
  "aqua": "#00ffff",
  "aquamarine": "#7fffd4",
  "azure": "#f0ffff",
  …
}

To create the diagram of CSS colors for the article, I needed to loop through the object : in other words, extract it’s enumerable properties. That’s easily accomplished by using a variation of the for loop that uses in:

for (var key in cssColors) {
    …
}

If we want to print the result to the console for testing purposes, we could modify the script to the following:

for (var key in cssColors) {
    console.log(key)
}

You’ll see the expected result:

aliceblue
antiquewhite
aqua
aquamarine
azure
…

If we want to include the value of that particular property, we can add that by separating the two with a comma:

for (var key in cssColors) {
    console.log(key, cssColors[key])
}

The result:

aliceblue #f0f8ff
antiquewhite #faebd7
aqua #00ffff
aquamarine #7fffd4
azure #f0ffff

You could use this information to construct most anything you wished: see the CodePen for the CSS Named Colors for one example.

Possible Misuses and Limitations

One aspect of for…in is that it can also enumerate inherited properties, not just those that you might expect to be set on the object. You can protect your output from this by testing for hasOwnProperty:

for (var key in cssColors) {
  if (cssColors.hasOwnProperty(key)) {
    … do something …
  }
}

This will check that the property we’re looking for has been natively applied to the object, and only report on that property.

for…in can also have problems with arrays that have been expanded with empty slots: as a general rule, adding, removing or modifying properties during iteration is a bad idea.

JSON arrays composed of multiple objects need to be treated a little differently, which I will cover in the next article.

Photograph by Benjamin Disinger, used under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.