I'm doing a dataLayer push for e-commerce purchases. Following the GTM guide, the product items are in an array. The issue is pulling the data: all the guides I've seen mention using an array index -- e.g. transactionProduct.1.price
to get the price for the 2nd item. But is not a robust solution: what if the user buys 100+ items? I can't hard-code the array index for this reason. So, how do I dynamically capture the properties in this case? I think I need to use the Custom JavaScript User-Defined Variable, but what would that look like (an example would be helpful)?
I believe I've figured it out:
If our dataLayer push looks like this:
window.dataLayer.push({
'event' : 'purchase',
'ecommerce': {
'transaction': {
'actionField': {
// ...
},
'products': // an array of objects...
}
}
});
Then, this GTM Custom JavaScript variable will return a list (of prices for each item):
function(){
var productList = {{NAME_OF_DATA_VARIABLE_ON_GTM_OF_ENTIRE_PUSHED_OBJECT}}.transaction.products;
return productList.map(function (obj) {
return obj.price;
});
}