javascript 将 data-* 属性转换为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23703044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:25:26  来源:igfitidea点击:

Converting data-* attributes to an object

javascripthtmldata-binding

提问by CamelBlues

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

我正在使用HTML5的attr-data-*属性和相应的 javascript数据集

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.datasetreturns a DOM string map, the only way I can figure out how to convert it into an native object is:

由于HTMLElement.dataset返回 a DOM string map,我能弄清楚如何将其转换为本机对象的唯一方法是:

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.

现在我有一个对象数组,即[{feaux: "bar", fizz:"buzz"}....]我可以使用的对象。

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

但是,当我不将 转换DOM string map为对象时,数组不会被填充(即上面的代码不起作用)

Edit 2

编辑 2

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

仔细一看,它实际上是一个DOM string map,而不是一个object。更正原始问题中的错别字以反映这一点。

回答by Agung Prasetyo

You can use Object.assign

您可以使用Object.assign

Object.assign({}, element.dataset) 

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

对于不支持 Object.assign 的浏览器,你可以使用polyfill

回答by Collin Craige

Don't forget about JSON.stringify and JSON.parse.

不要忘记 JSON.stringify 和 JSON.parse。

var data = document.getElementById('someElement').dataset;
data = JSON.parse(JSON.stringify(data));

According to Mozillathis should work all the way back to IE 8 without a polyfill.

根据Mozilla 的说法,这应该可以在没有 polyfill 的情况下一直运行到 IE 8。

回答by PhilWilliammee

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

在 es6 中,您可以使用对象传播。
{ ...element.dataset }

回答by bob

Here's a little function to retrieve the element dataset as a normal object:

这是一个将元素数据集作为普通对象检索的小函数:

function datasetToObject(elem){
    var data = {};
    [].forEach.call(elem.attributes, function(attr) {
        if (/^data-/.test(attr.name)) {
            var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function (##代码##, ) {
                return .toUpperCase();
            });
            data[camelCaseName] = attr.value;
        }
    });
    return data;
}

Scooped up from: Get list of data-* attributes using javascript / jQuery

摘自: Get list of data-* attributes using javascript / jQuery