How to dynamically return product array with Google Tag Manager and standard enhance e-commerce data layer using a lookup table

In this article, I’ll show you how to create a dynamic data layer variable to return the products array for each e-commerce action (e.i impressions, add to cart, checkout, etc…). Credit goes to Simo Ahava. He gave me this tip while answering a question I asked on the slack measure channel.

The issue: multiple data layer variable returning the same product array

When you want to return the products array with a standard Google Analytics Enhanced Ecommerce data layer, you have to create multiple data layer variables. More precisely, you have to create a data layer variable for each e-commerce action. Let’s take a look at the hierarchy of standard google e-commerce data layer JavaScript objects to understand better the issue I’m describing.

Here is the e-commerce object of purchases action:

‘ecommerce’: { ‘purchase’: { ‘actionField’: { ‘id’: ‘T12345’,
‘affiliation’: ‘Online Store’, ‘revenue’: ‘35.43’,
‘tax’:‘4.90’, ‘shipping’: ‘5.99’, ‘coupon’: ‘SUMMER_SALE’ }, ‘products’: [{ product one here },{ product two here }] } }

Here is the e-commerce object of checkouts action:

‘ecommerce’: { ‘checkout’: { ‘products’: [{ products here }] } }

If you want to return the products array for each one of these actions you will need to go through the ecommerce object, then a second level object which is different for each action: purchase and checkout. You will end up creating a specific Data Layer Variable for each e-commerce action:

Data Layer Variable

It can be even worth if you try to capture specific variables within the products array. When you have a container with hundred of elements saving few variables is always a good thing.

That’s why I looked for a way to always return the products array independently of the e-commerce action.

The solution: e-commerce event action lookup table

Simo came up with a nice and easy solution using a lookup table associated with event action. The lookup table takes action ecommerce event as Input and javascript object as Output. The following capture speaks for itself:

google tag manager lookup table

then you can pass the lookup table as a variable into your main products variable:

Google Tag Manager Data Layer Variable

Summary

Nothing fancy, but when working with a standard data layer e-commerce implementation, it can help save few variables. It is also an interesting mechanic to share as it is a good example of how you can use a lookup table. Ultimately it is also a good remember that you should ALWAYS ALWAYS attached an event variable which each data layer push.