简体   繁体   English

将 element.dataset (一个 DOMStringMap 对象)转换为“真实的” JSON object in vanilla JavaScript?

[英]Converting element.dataset (a DOMStringMap object) into a “real” JSON object in vanilla JavaScript?

Like explained in a similar StackOverflow question , in vanilla JavaScript, I can do the following:就像在类似的 StackOverflow 问题中解释的那样,在 vanilla JavaScript 中,我可以执行以下操作:

var data = Object.assign({}, element.dataset);

... in order to get all data-* attributes as an object. ...为了将所有data-*属性作为 object 获取。

However, the resulting object is not a "real" JSON object, booleans and numbers are surrounded by quotes.但是,生成的 object 不是“真正的” JSON object,布尔值和数字都用引号括起来。

<div id="my-element"
    data-string="It's OK."
    data-bool="true"
    data-number="10">
</div>

Here is the comparison between vanilla JavaScript and jQuery:这是香草 JavaScript 和 jQuery 之间的比较:

香草

jQuery

I supposed that in jQuery, jQuery('#my-element').data() is doing the heavy job of "lifting" the data before returing the actual JSON.我认为在 jQuery 中, jQuery('#my-element').data()在返回实际的 JSON 之前完成了“提升”数据的繁重工作。

Since I'd like to use ES6 and not jQuery, and I don't want to reinvent the wheel (parsing that values using regex/conditions), I'm asking if there is a quick way to do this job .由于我想使用 ES6 而不是 jQuery,并且我不想重新发明轮子(使用正则表达式/条件解析该值),我想问是否有一种快速的方法来完成这项工作

The data processing in jquery is done in getData() function in data.js jquery 中的数据处理在 data.js 中的getData() function 中完成

here is the code from JQuery library:这是 JQuery 库中的代码:

function getData( data ) {
    if ( data === "true" ) {
        return true;
    }

    if ( data === "false" ) {
        return false;
    }

    if ( data === "null" ) {
        return null;
    }

    // Only convert to a number if it doesn't change the string
    if ( data === +data + "" ) {
        return +data;
    }
    //Replaced rbrace with regex value.
    if ( /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/.test( data ) ) {
        return JSON.parse( data );
    }

    return data;
}

you can use this function and update your data.您可以使用此 function 并更新您的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM