2

If I have a set of key/value pairs like this:

WX Code     WMO WX Code Description
-------     -----------------------
00      No significant weather
04      Haze
10      Mist
20      Fog detected in last hour
21      Precip detected in last hour
22      Drizzle detected in last hour
23      Rain detected in last hour
24      Snow detected in last hour

that I want to access as an array by the integer code, what is the best way to format the array? If I try this

var arrWXcodes = [
{00:"No significant weather"},
{04:"Haze"},
{10:"Mist"},
{20:"Fog detected in last hour"},
{21:"Precip detected in last hour"},
{22:"Drizzle detected in last hour"},
{23:"Rain detected in last hour"},
{24:"Snow detected in last hour"}];

And I try to access the array to get, say "Haze" like so, I don't get what I want. I want to access the array by the key's integer value, not the position in the array

arrWXcodes["04"]
undefined
arrWXcodes[04]
Object { 21: "Precip detected in last hour" }

What would be the best data structure and access method to be able to use an integer key to access the array and get the expected value?

2 Answers2

8

Drop the array of objects and just have one main object:

var arrWXcodes = {
    "00": "No significant weather",
    "04": "Haze",
    ...
}

You can then access them properties by using arrWXcodes["00"], etc.

The reason you get a different result than expected in your own code when passing in an integer is because doing this references the index of the array and not the property name. 0 in the above example is "No significant weather", whereas "Haze" is 1 and not 4. Index 4 (the 5th item in the array) is your object with the value "Precip detected in last hour".

If you really want to be able to access the values with an integer you can convert the number to a string by using "" + 4, however this will generate "4" and not "04", so if your key names are in that structure you'd need to implement something like this: How can I pad a value with leading zeros?

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
1

Basically, you are defining an array of objects. And if you go by index 04 is the 5th element: {21:"Precip detected in last hour"}. And the index "04" is not defined in an array. An Array is like an object with integer key and its values: arrWXcodes={0:{00:"No significant weather"},1:{04:"Haze"}...}

Instead of using an array, you should use an object

arrWXcodes={
    "00":"No significant weather",
    ....
};
Thomas Junk
  • 5,588
  • 2
  • 30
  • 43