How can I convert dataset property names to data attribute names?

Viewed 344

I have an object with some keys and values, intended to be assigned to the dataset property of an HTML element. I would like to get the names of the data attributes that would be produced from those keys, as described where it says "camelCase to dash-style" in the "Name Conversion" section of the MDN dataset documentation.

How can I convert from dataset property names to data attribute names? I came up with something that works, which I put in an answer, but I'm wondering if there is a simpler or more elegant way, maybe involving a built-in function that I somehow overlooked.

I am looking for either a function that converts an individual name, or a function that converts an object with key-value pairs.

2 Answers

My function for converting an individual name:

const dataAttributeFromDatasetProperty = attr =>
    `data-${attr.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)}`;

My function for converting an object:

const dataAttributesFromDataset = dataset =>
    _.mapKeys(
        dataset,
        (value, attr) => `data-${attr.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)}`
    );

It uses lodash's _.mapKeys function.

I mean, theoretically you could just get the .outerHTML and grab the data tags off of it that way.

var test = document.createElement('span');

test.dataset.myTestDataElement = 'weee';
test.dataset.mySecondThing = 'data-test do not match me';

var html = test.outerHTML;

html.replace(/(data-[^=]+)=/g, function(_, name, _, _){
  console.log(name);
});

Related