Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access object using dynamic key? [duplicate]

Tags:

javascript

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 
like image 926
Venkat Papana Avatar asked Aug 03 '11 04:08

Venkat Papana


People also ask

How do you access an object dynamically?

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] .

How do you access objects using variables?

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] .

How do you add a key value pair in an object dynamically?

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.


2 Answers

You can access objects like arrays:

alert(o[key]); 
like image 183
OverZealous Avatar answered Oct 04 '22 20:10

OverZealous


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.

like image 23
Andrius Virbičianskas Avatar answered Oct 04 '22 20:10

Andrius Virbičianskas