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
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
To add dynamic key-value pairs to a JavaScript array or hash table, we can use computed key names. const obj = {}; obj[name] = val; to add a property with the value of name string as the property name. We assign val to as the property's value.
You can access objects like arrays:
alert(o[key]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With