How can I use destructering in JavaScript with dataset property?

Viewed 138

I want to assign two variables with destructering. My current attempt looks like this:

const { textContent, dataset.value: dataValue } = dropDown;

dropDown is a DIV node with an data-attribute(value) and inner text.

This obviously didn't work out, I got the error message Uncaught SyntaxError: missing : after property id. Because of this, I changed the code like this:

const { textContent, dataset: dataValue } = dropDown;

This did work better, textContent was successfully declared with the correct variable. However, I want that the variable dataValue gets assigned with the content of the data-attribute(dataset.value) of the DIV node. After running my above code, I also found out that the dataset property contains a DOMStringMap.

This is the result, the code outputs: { "textContent": "Select", "dataValue": { "value": "none" } }

How am I able to assign the content of the dataset.value to the variable dataValue directly with destructering?

1 Answers

Nested objects can be destructured like this,

const object = { "textContent": "Select", "dataset": { "value": "none" } };

let {textContent, dataset: {value: dataValue }} = object;
console.log(dataValue);

Related