How to access object using dynamic key?

Javascript

Javascript 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVenkat PapanaView Question on Stackoverflow
Solution 1 - JavascriptOverZealousView Answer on Stackoverflow
Solution 2 - JavascriptAndrius VirbičianskasView Answer on Stackoverflow
Solution 3 - JavascriptLanceView Answer on Stackoverflow