Nicholas
Nicholas

Reputation: 37

How to parse html data to an array in a different formats

I'm using vanilla javascript to parse HTML data attributes and after that, I need to parse to a different list in a different format. how can I parse them as array list with all products

HTML

<div>
   <img src="img1.jpg" />
   <div class="description">Lagavulin 16 Year Old</div>
   <button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">
      Add To Cart
   </button>
</div>
<div>
      <img src="img2.jpg" />
      <div class="description">Ardbeg</div>
         <button class="add-to-cart" data-product-id="10" data-product-title="Ardbeg" data-category="Scotch">
            Add To Cart
         </button>
      </div>
</div>

JS:

Array.from(
   document.getElementById("main-menu")
   .getElementsByTagName("li")
).forEach((x) =>
   (x.onclick = () =>
   console.log({
      event_name: "menu item clicked",
      menu_item: x.innerText,
   }))
);

Im expecting to create an array with all the products that would look like this

“name”: <str>, mandatory
“id”: <int>, mandatory
“price”: <float>, mandatory
“brand”: <str>, optional
“list”: <str>, optional
“position”: <int>, optional

Upvotes: 0

Views: 391

Answers (1)

vsync
vsync

Reputation: 130670

You can extract the information from the HTML as the below code shows, but I don't understand from where you are expecting to get brand & position since you there's no such information in the HTML.

var itemsElems = document.querySelectorAll('.add-to-cart');

var result = [...itemsElems].reduce((acc, elm) => {
  var {productId: id, productTitle: name, category} = elm.dataset || {};

  acc.push({
    id: +id,  // cast to number
    name,
    category,
  })
  
  return acc
}, []);

console.log(result)
<div>
  <img src="img1.jpg" />
  <div class="description">Lagavulin 16 Year Old</div>
  <button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">
      Add To Cart
   </button>
</div>
<div>
  <img src="img2.jpg" />
  <div class="description">Ardbeg</div>
  <button class="add-to-cart" data-product-id="10" data-product-title="Ardbeg" data-category="Scotch">
     Add To Cart
  </button>
</div>

Upvotes: 1

Related Questions