87

How to access an object using a variable as key. Here is my code sample:

var o = {"k1": "111", "k2": "222"};
alert(o.k1); //working fine
var key = "k"+1; alert(key); // k1
alert(o.key); //not working
0

3 Answers 3

158

You can access objects like arrays:

alert(o[key]);
Sign up to request clarification or add additional context in comments.

Comments

15

Change the last line to: alert(o['k1']); or alert(o[key]); where key is your dynamically constructed property key.

Remember you can access object's properties with array notation.

Comments

2

Consider using a for...in loop

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.