javascript - Converting data-* attributes to an object -
i'm playing around attr-data-* attributes of html5 , corresponding javascript dataset
i'm doing alot of dynamic form processing, end getting stuff this:
<input data-feaux="bar" data-fizz="buzz"/>
since htmlelement.dataset
returns dom string map
, way can figure out how convert native object is:
var obj = json.parse(json.stringify(input_el.dataset))
is there better way this?
edit:
why want this? let's have many, many of these elements. want loop through them , push them array processing later, i.e.
elements = document.queryselectorall("input") my_data_array = [] for(var = 0; < elements.length; i++) { my_data_array.push(elements[i].dataset) }
now have array of objects, i.e. [{feaux: "bar", fizz:"buzz"}....]
can work with.
however, when don't convert dom string map
object, array doesn't populated (i.e. code above doesn't work)
edit 2
looking closer, dom string map
, not object
. correcting typos in original question reflect this.
you can use object.assign
object.assign({}, element.dataset)
for browsers doesn't support object.assign can use polyfill
Comments
Post a Comment