0

This is a quick question, I hope you could help me with.

How can I use a string to navigate into a object?

If I have this:

var string = something;

And a object like this:

var this = {
    something: {
        other: "okay"
    }
}​;

How can I then use the string to do like this:

this.+string+.other

Which would be the same as:

this.something.other

?? Not a quick one maybe, but do you understand where I'm going?? :-)

1
  • 1
    careful with using this as a variable name. Strange things will happen, or nothing will happen at all! Commented Jun 9, 2012 at 21:56

2 Answers 2

1

Try using [] below,

var _this = {
    something: {
        other: "okay"
    }
}​;

_this[string].other

Note: changed var name to _this as var this = <..something..> will throw you an error. Also this means currect execution object/window object in javascript.

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

2 Comments

+1 I also think that using this as a variable name is not that good.
Thanks for the quick reply. The variables were just for the sake of example, but I should have been more careful :)
1

Use square bracket notation:

var this[something].other

Comments

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.