0

How can you reference a javascript object indirectly?

Suppose:

<div id="foo" data-munchy="bar" data-crunchy="baz">FooBar</div>

<script>
document.getElementById("foo").onclick = function() {
    tempVariable = 'munchy';
    console.log(this.dataset.tempVariable);
}
</script>

How can I access this.dataset.{someVariable}? In this case, this.dataset.tempVariable

Is it only possible using eval or window?

pbarney
  • 2,529
  • 4
  • 35
  • 49
  • You want `this.dataset[tempVariable]`. – Mikey Apr 27 '18 at 19:21
  • 1
    `this.dataset[tempVariable]` for your example is the same as `this.dataset.munchy`. – CRice Apr 27 '18 at 19:21
  • 1
    Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – lealceldeiro Apr 27 '18 at 19:27
  • @lealceldeiro it appears to be. I don't know why I had so much trouble finding it. Maybe the wording of the question isn't relatable to people who aren't familiar with the concept. – pbarney Apr 28 '18 at 03:41

1 Answers1

4

Use square bracket notation:

this.dataset[tempVariable];

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
  • 1
    @VictorStoddard - no, that will look for the string `tempVariable` - literally what OP originally had: `this.dataset.tempVariable` – tymeJV Apr 27 '18 at 19:39
  • 1
    This is great. I didn't realize they could be accessed both properties and arrays. Thanks, @Kevin. – pbarney Apr 28 '18 at 03:30