0

When I have an object and I want to refer to a property within it, I can use e.g.

objectName.propertyName 

and when I have a "subproperty" I can use

objectName.propertyName.propertyName

But how can I use a variable with this syntax ?

objectName.myvar.propertyName

Obviously this does not work. The variable is interpreted as a string itself and calls for the value with the key: "myvar".

How do I have to declare the variable using this syntax to be used like this:

var myvar = qwertz; objectName.myvar.propertyName 

and be interpreted as

var myvar = qwertz; objectName.qwertz.propertyName 

1 Answer 1

2

Use the bracket notation:

var myvar = 'qwertz';
var result = objectName[myvar].propertyName; 
// equivalent to objectName.qwertz.propertyName
Sign up to request clarification or add additional context in comments.

1 Comment

Thx I didnt remove the dot between objectName and [myvar] when i used the brackets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.