0

I am referencing this post:

are there dictionaries in javascript like python?

My dictionary looks like this:

        states_dictionary = {
         "1":["60","purple","1t"],
         "2":["50","blue","2t"],
         "3":["40", "red","3t"],
         "4":["30","yellow","4t"],
         "5":["20","black","5t"],
         "6":["10", "green","6t"],
         "7":["10", "orange","7t"]
    };

I am have a variable called reading that on first iteration, is "1". I want to get the color corresponding to this variable using a dictionary.

I use:

color = states_dictionary.reading[1]

However, I get an error Uncaught TypeError: Cannot read property '1' of undefined

Why is this?

Community
  • 1
  • 1
huhh hhbhb
  • 573
  • 3
  • 7
  • 19

1 Answers1

1

What you are asking for here:

color = states_dictionary.reading[1];

Is the property called reading of the object states_dictionary. states_dictionary does not have a property called reading, so that returns undefined. You can't call any properties of undefined, so you get the error you observe.

If reading is a variable like this:

var reading = 1; // or even "1"

Then you can do this:

color = states_dictionary[reading][1];

And color will get the value purple.

Use the bracket notation to dynamically access a property using a variable rather than the dot notation. For example these:

var foo = someObj.Foo;
var foo = someObj["Foo"];

Are equivalent. But these two:

var bar = "Foo";
var foo = someObj.bar;
var foo = someObj[bar];

Are not.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171