【问题标题】:How to pass from string to object with javascript?如何使用javascript从字符串传递到对象?
【发布时间】:2021-07-12 01:05:09
【问题描述】:

我有以下代码:

    const burger = `<div class="card" data-id="42" data-price="15" data-category="popular">`

我需要以下对象:

    const obj = { id: 42, price: 15, category: 'popular' }

使用此功能:

let regex = /(?<name>\w+)="(?<value>\w+)"/g;
let results = burger.matchAll(regex);

for(let result of results) {
  let {name, value} = result.groups;
  let valores = `${name}: ${value}`;
  console.log(valores)
}

我得到以下信息,但这不是我想要的

    > "class: card"
    > "id: 42"
    > "price: 15"
    > "category: popular"

【问题讨论】:

    标签: javascript regex string object split


    【解决方案1】:

    您可以使用DOMParser 来解析 HTML,获取第一个子元素并遍历所有属性。

    要将数字和布尔字符串转换为相应的类型,我们可以使用isNaN 和简单的字符串比较。

    parseInt() 用于将字符串转换为数字,JSON.parse() 用于将字符串转换为布尔值。

    const burger = `<div class="card" data-id="42" data-price="15" is-author-spectric="true" data-category="popular"><div class="card-category">Popular</div><div class="card-description"><h2>The best burger in town (15€)</h2></div></div>`;
    
    const parser = new DOMParser().parseFromString(burger, "text/html");
    const elem = parser.body.firstChild;
    var json = {};
    for (var i = 0; i < elem.attributes.length; i++) {
        var attrib = elem.attributes[i];
        json[attrib.name] = !isNaN(attrib.value) ? parseInt(attrib.value) : attrib.value == "true" || attrib.value == "false" ? JSON.parse(attrib.value) : attrib.value;
    }
    
    console.log(json);

    【讨论】:

    • 以下函数给了我以下结果: Object { class: "card", data-id: 42, data-price: 15, is-author-spectric: true, data-category: "流行”},我需要它如下:{ id:42,价格:15,类别:'流行'}
    • @Hipólito 您需要重命名属性名称并删除您不想显示的名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2018-08-25
    • 2021-05-05
    • 2020-11-23
    • 2015-10-10
    相关资源
    最近更新 更多