Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access object property using variable [duplicate]

Tags:

I have an object

var Messages = { 'fullName' : 'Tell us your cool name dude..! e.g. Yousuf Iqbal', 'userName' : 'Choose a catchy username. Remember! It should be available :)', 'password' : 'Choose a top secret password with special chars, numbers and alphabets', 'rePassword' : 'Retype the password you just typed. But, don\'t try to copy!', 'bYear' : 'Tell the year, in which this bomb blasted' }; 

and a variable..

var attribute = $('#userinfo form input').attr('name'); 

now i want to select Messages object property using this variable like this..

var message = Messages.attribute; 

but Its not working.. and have also tried the following..

var message = Messages+'.'+attribute; 
like image 543
Yousuf Memon Avatar asked Jun 29 '12 04:06

Yousuf Memon


People also ask

How do you access the properties of an object with a variable?

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 dynamically access object property in typescript?

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


2 Answers

Square brackets:

message = Messages[ attribute ]; 
like image 172
Pointy Avatar answered Oct 18 '22 21:10

Pointy


var message = Messages[attribute]; 
like image 37
Lior Cohen Avatar answered Oct 18 '22 21:10

Lior Cohen