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