#GTMTips: Access Array Members in the Data Layer

How to access individual array indices or members in Google Tag Manager Data Layer variable model.

In JavaScript, if you want to access an Array member, you use square bracket notation to retrieve the value stored at a specific index. Indices are numbered in order, with the first index always being at location zero (0). This means that to get the first value stored in Array simo, you’d use something like:

var firstValue = simo[0];

In Google Tag Manager, you can push Arrays into the Data Layer. However, the Data Layer Variable type, which you use to retrieve values stored in the Data Layer, does not support the aforementioned square bracket notation in its fields. Instead, you need to use a special, proprietary format to access Array members.

Tip 28: Use dot notation to access Array members in the Data Layer

As usual, this is a simple tip. Just substitute the square brackets you’d use in vanilla JavaScript with dots. So classic JavaScript Array[0].name becomes Array.0.name in Google Tag Manager.

Do note that this also means that you can’t use square bracket notation to access object literal properties either. You need to use dot notation all the way through.

A practical example is in Ecommerce tracking. To get the SKU of the first product in an ecommerce.purchase object (Enhanced Ecommerce), you’d use this in a Data Layer Variable:

ecommerce.purchase.products.0.id

That retrieves the value stored in the id key of the first product in the products Array of the Enhanced Ecommerce purchase object.