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;
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 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] .
Square brackets:
message = Messages[ attribute ];
var message = Messages[attribute];
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