3

Possible Duplicate:
Javascript create variable from its name

The code below checks to see if the javascript object form_errors has the property whose name is specified by this.name, where this refers to a text input

if (form_errors.hasOwnProperty(this.name)) {
  alert(form_errors.<this.name>;
}

How can I access the property without hard-coding the property name but leaving in the generalized form this.name ? Thanks.

0

1 Answer 1

10

Use brackets:

form_errors[this.name]

You can access any property of an object by passing in a string with its name. For instance, foo.bar and foo['bar'] have the same result.

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

4 Comments

Just keep in mind foo['i-like-hyphens'] can only be accessed with brackets.
Actually in javascript everything is arrays. Even JSON are arrays with different data types. So Braces are the best option.
@abhishek, You're incorrect. Everything in JS is an object, it just happens that arrays are a special form of object. Try typeof [] in the console.
@abhishek, aside from the type hierarchy remark, I'd say that whether to use brackets or the dot notation is a question of circumstances. In case of statical accesses, using the dot notation is 3 characters shorter and doesn't imply any strings (which is more refactor-friendly), so in my opinion, it's better to stick to it until you come to a point where it's impossible (such as the situation noted by Dennis, or OP's situation).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.