How to access object using dynamic key?
JavascriptJavascript Problem Overview
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
Javascript Solutions
Solution 1 - Javascript
You can access objects like arrays:
alert(o[key]);
Solution 2 - Javascript
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.
Solution 3 - Javascript
Consider using a for...in
loop