3

I have an input field that looks like this:

<input placeholder="Card Number" name="cc-number" data-stripe="number" class="add-card-form__card-number input" value="">

I'd like to do something like this:

onFocus (e) {
  const { 'data-stripe': name, value } = e.target
  // do something with `name` and `value`
}

I know I can use e.target.getAttribute('data-stripe'), but that defeats the purpose of destructuring. Any ideas how to do this?

Here it says exactly what I'm doing. How to destructure object properties with key names that are invalid variable names?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alex Cory
  • 10,635
  • 10
  • 52
  • 62

2 Answers2

5

There's no data-stripe property in the DOM element. All data-XXX attributes are turned into properties of the dataset property. So you should use:

onFocus(e) {
    const { dataset: { stripe: name }, value } = e.target;
    // do something with name and value
}

It can also be accessed as an element of the attributes property, but since this is an array and the order is unpredictable, it's not useful for destructuring.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

This is not a hyphen issue, you are just not calling HTML DOM correctly. Even if your custom attribute was "stuff" you cannot access it as e.target.stuff. Your own link shows how to access hyphenated: attributes.

var {"data-stripe":{value:myVariableName}} = e.target.attributes;
//myVariableName="number"
Alex Gulakov
  • 87
  • 1
  • 5