0

I am trying to get a property value of a Javascript object.

My code goes like this:

for (key in map.regions) {
    console.log(key);
    console.log(states);
    console.log(states.key);
}

The variable key will be something like, "US-VA"

The variable states should look something like this:

Object {US-VA: Object, US-PA: Object, US-TN: Object, US-ID: Object, US-NV: Object…}

(This is from Chrome).

However whenever I use console.log on states.key - which should get the object that the key represents, I instead get undefined.

What am I doing wrong here? How do I get the values from the states variable that correspond with the value in key?

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232

2 Answers2

5

If your browser console log is showing that states is defined like you say, use states[key] instead of states.key.

states.key will find the property with the literal key "key".

states[key] will find the property with the key that has the value of the variable key.

Trott
  • 66,479
  • 23
  • 173
  • 212
0

You need to use Bracket notation here to get value by key

console.log(states[key]);

and why you need to do this check here JavaScript property access: dot notation vs. brackets?

Community
  • 1
  • 1
Karan Patyal
  • 371
  • 3
  • 8