5

I'm trying to replicate a "feature" of PHP (And in most languages) in Javascript.

Here it is in PHP:

$objectName = 'ObjectA';

$someObject->$objectName->someMethod();

Basically using a string variable to reference an object variable.

So in Javascript, I was hoping to do something like:

var objectName = "ObjectA";

someObject.[objectName].someMethod();

Anyone know how to do this? Or if its even possible?

1 Answer 1

14

You almost have it, just remove the first ., like this:

var objectName = "ObjectA";
someObject[objectName].someMethod();

If you want to search for more info around this, it's called bracket notation.

Sign up to request clarification or add additional context in comments.

2 Comments

Gah. I was one damn character off. I didn't know what it was called or I would've Googled Bracket Notation. Thanks a lot!
This does not work beyond depth one. If you have a string like "Object.a.attribute.val" you cannot object[str] the last attribute. How to achieve this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.