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.

Community
  • 1
  • 1
tamakisquare
  • 16,659
  • 26
  • 88
  • 129

1 Answers1

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.

zneak
  • 134,922
  • 42
  • 253
  • 328
  • 2
    Just keep in mind `foo['i-like-hyphens']` can only be accessed with brackets. – Dennis Aug 16 '11 at 19:04
  • Actually in javascript everything is arrays. Even JSON are arrays with different data types. So Braces are the best option. – abhishek Aug 16 '11 at 19:09
  • 4
    @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. – zzzzBov Aug 16 '11 at 19:10
  • 1
    @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). – zneak Aug 16 '11 at 19:54