curly_brackets
curly_brackets

Reputation: 5598

Create object by string

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?? :-)

Upvotes: 0

Views: 397

Answers (2)

austinbv
austinbv

Reputation: 9491

Use square bracket notation:

var this[something].other

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

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.

Upvotes: 1

Related Questions