0

I have the following code:

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

i need the following object:

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

With this function:

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)
}

I get the following, but it is not what I want

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

1 Answer 1

2

You can make use of a DOMParser to parse the HTML, get the first child and loop through all attributes.

To convert number and boolean strings to their corresponding types, we can make use of the isNaN and simple string comparison.

parseInt() is used to convert the string to a number and JSON.parse() is used to convert the string to a boolean.

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);

Sign up to request clarification or add additional context in comments.

2 Comments

the following function gives me the following result: Object { class: "card", data-id: 42, data-price: 15, is-author-spectric: true, data-category: "popular" } and I need it to be as follows: { id: 42, price: 15, category: 'popular' }
@Hipólito You'll need to rename the attribute names and remove the ones that you don't want shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.