Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Object.assign

Object.assign({}, element.dataset) 

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...