1

Is there an easier way to access an object property in JavaScript using a variable?

Here's what doesn't work:

var element_id = this.data().element_type + 'id';

Here's how it does work, which seems convoluted.

var element_id;
if ( element_type == 'assignment' ) {
    element_id = this.data().assignmentid;
} else if ( element_type == 'question' ) {
    element_id = this.data().questionid;
} else {
    element_id = this.data().answerid;
}
Kevin
  • 79
  • 7

1 Answers1

3

Do it like this:

var element_id = this.data()[element_type + 'id'];

This is the alternative syntax to dot property access, which allows you to specify a string denoting the name of the property.

The reason your approach didn't work is because this.data().element_type + 'id' means first evaluate this.data().element_type and then add 'id' to it.

JCOC611
  • 19,111
  • 14
  • 69
  • 90