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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.