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
- In GTM, go to Variables
- Click New
- Name the variable: JS – ecommerce.items[0].item_name
- Click Variable Configuration → Choose Custom JavaScript
- 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 Name | Variable |
| 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
- Click Preview in GTM
- Trigger the “Add to Cart” action on your website
- Open Tag Assistant
- 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.