I want to use a variable to hold a key name for an object so I can do the below.
var obj = {name:'john', age: 8}
var holder
holder can be name or age so obj.holder
can return 'john'
or 8
depending on what I set holder
How do I set a variable to be a object's key so I can access an object dynamically in javascript?
Just try with bracket notation when accessing the object properties:
var obj = {name:'john', age: 8}
var holder = 'name';
obj[holder]; // john
holder = 'age';
obj[holder]; // 8
var obj = {name:'john', age: 8};
var index = "john";
var holder = obj[index];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.