Dynamically Accessing Object Entries

A task I had in a recent project was to retrieve and display current weather data on a webpage. This was done using the OpenWeatherMap API, which lets you find current and forecasted weather data for a given location.

Now the API call for current weather data returns an object with all the information you might need to know. It has the coordinates, country name, wind speed and direction, even an icon visualizing the current weather. But, if you want to know if it’s raining or snowing, and the level of precipitation, that’s annoyingly difficult to find.

Incredibly annoyingly, the returned object may or may not have an entry for rain or snow, depending on current conditions. If there’s nothing going on, there’s no object entry. And depending on the conditions, the name of the entry can change.

So how can we deal with this? How can we retrieve data from an object entry when we don’t even know the key name? The simple method I found only works if you know the content of the object entry, and if there’s only one entry you don’t know the name of. The main two components are the object.keys() method, and the square bracket notation for objects, like object[var], which lets use search an object using a variable storing the object key rather than the manual string.

First, we have to manually create an array of all the object keys we expect to consistently find in the object. This should be every key except for the one mystery key.

Next, we use object.keys(response) to get an array of all the object’s keys. (You might see where this is going).

Use a for loop to check each key from the object against every element in our array. If a key doesn’t have its pair in the comparison array, store that string in a variable. If you go through the entire loop, the object entry doesn’t exist.

Next, we can use the bracket [] notation to search the object with our new variable. object[var], where var is our mysterious entry, will return that key’s data.

And there you have it. one of the few ways you can deal with an annoying problem I’m sure many people have had with API calls.

Relevant resources:

Object.keys() — JavaScript | MDN (mozilla.org)

Property accessors — JavaScript | MDN (mozilla.org)