Search code examples
javascriptgoogle-tag-manager

How to setup javascript in Google Tag Manager to capture order details from multiple products in an order


I am implementing a tag through GTM for a vendor (Impact Radius) that needs to capture all of the products and product details from an order.

I can populate for one item, but I don't know how to cycle through the data layer to capture more than one item like below.

code to be implemented

items: [
    {
        subTotal: subTotal,
        category: "category",
        sku: "sku",
        quantity: quantity,
        name: "name"
    },
    {
        subTotal: subTotal,
        category: "category",
        sku: "sku",
        quantity: quantity,
        name: "name"
    }
]

Here are the data layer variables:

  "transactionProducts":       
  [
    {
      "id": 3142109626432,
      "sku": "CL7725-1",
      "name": "Roger - Black",
      "price": "75.00",
      "quantity": 1,
      "category": "sunglasses",
      "brand": "Carolina",
      "variant": "Black",
      "variant_id": 26263687790656
    },
    {
      "id": 3142106480704,
      "sku": "CL7644-5",
      "name": "Paco - Clear Champagne",
      "price": "75.00",
      "quantity": 1,
      "category": "sunglasses",
      "brand": "Carolina",
      "variant": "Clear Champagne",
      "variant_id": 26263675174976
    }
  ]

How do I solve this problem?


Solution

  • You need to map your dataLayer variable to the desired structure, using Array map method.

    Assuming, your transactionProducts variable is assigned to a Data Layer Variable called transaction products, you can loop this array like this:

    var output = {{transaction products}}.map(function(e) {
        return {
          subTotal : e.price * e.quantity,
          category : e.category,
          sku : e.id,
          quantity : e.quantity,
          name : e.name
        };
      });
    

    Altough you haven't specified, I've assumed, that subTotal is calculated by multiplying price and quantity, but you can adjust the code to your needs.