Google Tag Manager

⌘K
  1. Home
  2. Google Tag Manager
  3. Advanced Google Tag Manag...
  4. Extracting Values from Arrays in the Data Layer Using Custom JavaScript Variables (GTM)

Extracting Values from Arrays in the Data Layer Using Custom JavaScript Variables (GTM)

Objective

To extract specific values (like item_name, item_id, price, etc.) from a Data Layer array (e.g. ecommerce.items[0]) using Custom JavaScript Variables in Google Tag Manager — especially useful for ecommerce events like add_to_cart and purchase.

Why Use Custom JavaScript?

Google Tag Manager Data Layer Variables cannot directly access arrays like ecommerce.items[0].item_name.

→ Instead, you can use Custom JavaScript Variables to manually pull out values from arrays.

Step 1: Sample Data Layer Array

Here’s an example pushed to the dataLayer:

window.dataLayer.push({

  event: “add_to_cart”,

  ecommerce: {

    items: [

      {

        item_name: “Sneakers”,

        item_id: “SHOE001”,

        price: 89.99,

        quantity: 1

      }

    ]

  }

});

You want to extract item_name = Sneakers from the first item.

Step 2: Create a Custom JavaScript Variable

  1. In GTM, go to Variables
  2. Click New
  3. Name the variable: JS – ecommerce.items[0].item_name
  4. Click Variable Configuration → Choose Custom JavaScript
  5. Paste this code:

function() {

  try {

    var items = window.dataLayer.find(obj => obj.ecommerce && obj.ecommerce.items);

    return items.ecommerce.items[0].item_name || undefined;

  } catch(e) {

    return undefined;

  }

}

Step 3: Create Similar Variables (Optional)

You can create additional variables using similar logic:

  • For item_id:

function() {

  try {

    var items = window.dataLayer.find(obj => obj.ecommerce && obj.ecommerce.items);

    return items.ecommerce.items[0].item_id || undefined;

  } catch(e) {

    return undefined;

  }

}

  • For price:

function() {

  try {

    var items = window.dataLayer.find(obj => obj.ecommerce && obj.ecommerce.items);

    return items.ecommerce.items[0].price || undefined;

  } catch(e) {

    return undefined;

  }

}

Step 4: Use These Variables in a GA4 Event Tag

When building your GA4 – add_to_cart tag:

Parameter NameVariable
item_name{{JS – ecommerce.items[0].item_name}}
item_id{{JS – ecommerce.items[0].item_id}}
price{{JS – ecommerce.items[0].price}}

Step 5: Preview and Test

  1. Click Preview in GTM
  2. Trigger the “Add to Cart” action on your website
  3. Open Tag Assistant
  4. Make sure:
  • The Custom JS variables return correct values
  • The GA4 event tag fires with the right parameters

Note

  • You can extract from any index: items[0]items[1], etc.
  • You can extract arrays dynamically using map() if tracking multiple items (advanced).
  • Always wrap in try…catch to avoid JS errors breaking the tag.

How can we help?