将data- *属性转换为对象 [英] Converting data-* attributes to an object
问题描述
我正在玩 attr -data- * HTML5的属性和相应的javascript 数据集
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"/>
由于 HTMLElement.dataset
返回 DOM字符串映射
,我能弄清楚如何将其转换为本机对象的唯一方法是:
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))
有更好的方法吗?
编辑:
为什么我想要这样做吗?假设我有很多很多这样的元素。我想循环遍历它们并将它们推入一个数组以便稍后处理,即
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)
}
现在我有一个对象数组,即 [{feaux: bar,fizz:buzz} ....]
我可以使用。
Now I have an array of objects, i.e. [{feaux: "bar", fizz:"buzz"}....]
that I can work with.
然而,当我不转换时 DOM字符串映射
到一个对象中,数组没有填充(即上面的代码不起作用)
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)
编辑2
仔细观察,它实际上是 DOM字符串映射
,而不是对象
。更正原始问题中的拼写错误以反映这一点。
Looking closer, it is actually a DOM string map
, not an object
. Correcting typos in the original question to reflect this.
推荐答案
您可以使用 Object.assign
Object.assign({}, element.dataset)
对于没有的浏览器不支持Object.assign你可以使用 polyfill
For browsers that doesn't support Object.assign you can use polyfill
这篇关于将data- *属性转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!