Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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
You can access objects like arrays:
alert(o[key]);
Add a comment
Change the last line to: alert(o['k1']); or alert(o[key]); where key is your dynamically constructed property key.
alert(o['k1']);
key
Remember you can access object's properties with array notation.
Consider using a for...in loop
for...in
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.