This small utility demonstrates transforming an object to data-* attributes for use in server templating. The data-* attributes match how a browser maps to JS, so you can use it and get back your original keys on the client from an element’s dataset property.
For example, in an Astro component:
---
import { dataset } from './dataset';
const data = { Example: "value", count: 10, backgroundColor: '#fff' };
const props = dataset(data);
// { 'data--example': 'value', 'data-count': 10, 'data-background-color': '#fff' }
---
<div id="example" {...props}>Example</div>And a script could read these back:
const el = document.getElementById('example');
el.dataset.
// ^ Example
// count
// backgroundColorN.B. There’s no way to serialize a number in HTML, so the count property in the example above returns a string on the client.