jqueryjsongoogle-datalayer

jQuery – loop DOM objects and pass them to dataLayer(json?)


I have to manually create my events for GA4, and I have a little knowledge of jQuery. I'm trying to loop through my DOM elements and pass the data from them to dataLayer (as I understand, that's json format?), that Google wants. My code looks like that (in simplified form):

function viewCartGA4() {
  let product = $('table.products tbody tr');
  dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
  dataLayer.push({
    event: "view_cart",
    ecommerce: {
      currency: "xxx",
      items: [
      {
        item_name: product.children().data("name"),
        item_id: product.children().data("code")
      }
      ]      
    }
  })
}

If there's only one table row, there's no problem, but how can I pass more than one to an array items required by Google? Tried to create an $.each function inside an array, to no avail.


I'm not a pro by any means, it just happened, that I cover things like that in my company. Tried to look through the Internet, I found only the opposite situation (to pass json data to the DOM elements/content). I have just the basic understanding of coding and coding concepts. Appreciate the help.


Solution

  • Assuming the supplied code works when there is a single table row, for many rows you would need to loop over each and map it to the desired object. jQuery has .map method that can used:

    function viewCartGA4() {
      // map each table row (tr) to an object
      const items = $('table.products tbody tr').map(function () {
        return {
          item_name: $(this).children('[data-name]').data("name"),
          item_id: $(this).children('[data-code]').data("code")
        };
      }).get(); // .get() turns this from a jQuery wrapped array into an unwrapped one
      
      dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
      dataLayer.push({
        event: "view_cart",
        ecommerce: {
          currency: "xxx",
          items: items // assign the mapped `items`
        }
      });
    }