Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 215
CamelBlues Avatar asked May 16 '14 19:05

CamelBlues


People also ask

Can data -* attribute contain HTML tags?

The data-* attribute is a Global Attribute, and can be used on any HTML element.

What is a data attribute?

In short, a data attribute is a single-value descriptor for a data point or data object. It exists most often as a column in a data table, but can also refer to special formatting or functionality for objects in programming languages such as Python.

What is the use of data attribute in HTML?

data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.

How get data attribute from Element?

Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.


2 Answers

You can use Object.assign

Object.assign({}, element.dataset)  

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

like image 146
Agung Prasetyo Avatar answered Sep 24 '22 09:09

Agung Prasetyo


in es6 you can use the object spread.
{ ...element.dataset }

like image 44
PhilWilliammee Avatar answered Sep 21 '22 09:09

PhilWilliammee