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

Answers:

Answer

You can access objects like arrays:

alert(o[key]);
Answer

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.

Answer

Consider using a for...in loop

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.