Search code examples
javascripthtmldata-binding

Converting data-* attributes to an object


I'm playing around with the attr-data-* attributes of HTML5 and the corresponding javascript dataset

I'm doing alot of dynamic form processing, so I end up getting stuff like this:

<input data-feaux="bar" data-fizz="buzz"/>

Since HTMLElement.dataset returns a DOM string map, the only way I can figure out how to convert it into an native object is:

var obj = JSON.parse(JSON.stringify(input_el.dataset))

Is there a better way to do this?

Edit:

Why would I want to do this? Let's say I have many, many of these elements. I want to loop through them all and push them into an array for processing later, i.e.

elements = document.querySelectorAll("input")
my_data_array = []
for(var i = 0; i < elements.length; i++) {
    my_data_array.push(elements[i].dataset)
}

Now I have an array of objects, i.e. [{feaux: "bar", fizz:"buzz"}....] that I can work with.

However, when I don't convert the DOM string map into an object, the array doesn't get populated (i.e. the code above doesn't work)

Edit 2

Looking closer, it is actually a DOM string map, not an object. Correcting typos in the original question to reflect this.


Solution

  • You can use Object.assign

    Object.assign({}, element.dataset) 
    

    For browsers that doesn't support Object.assign you can use polyfill