0

I am trying to get data like revenue, order value etc using the following code. Upon checking in the console I receive: "Uncaught TypeError: Cannot read property 'purchase' of undefined"

var revenue = 0;
var shipping = 0;
var tax = 0;
var orderID = 0;
var orderValue = 0;
var couponCode = "";

if (typeof dataLayer !== undefined && dataLayer.length > 0 && typeof dataLayer.ecommerce !== undefined) {
  orderID = dataLayer[0].ecommerce.purchase.actionField.id;

  revenue = parseInt(dataLayer[0].ecommerce.purchase.actionField.revenue) > 0 ? parseInt(dataLayer[0].ecommerce.purchase.actionField.revenue) : 0;

  shipping = parseInt(dataLayer[0].ecommerce.purchase.actionField.shipping) > 0 ? parseInt(dataLayer[0].ecommerce.purchase.actionField.shipping) : 0;

  tax = parseInt(dataLayer[0].ecommerce.purchase.actionField.tax) > 0 ? parseInt(dataLayer[0].ecommerce.purchase.actionField.tax) : 0;

  couponCode = dataLayer[0].ecommerce.purchase.actionField.coupon;

  orderValue = revenue - (shipping + tax);
}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • if dataLayer is an array shouldnt the check be `typeof dataLayer[0].ecommerce !== undefined`? or is it just a typo? – Suraj Rao Jul 10 '20 at 10:06
  • Updated the line to : if (typeof dataLayer !== undefined && dataLayer.length > 0 && typeof dataLayer[0].ecommerce !== undefined) - however i still get the same error message :/ – Josef Moucachen Jul 10 '20 at 10:27
  • what do you get if you console log `dataLayer`? – Suraj Rao Jul 10 '20 at 11:42
  • The following: (2) [{…}, {…}, push: ƒ] 0: pagePostAuthor: "grafikfabriken" pagePostType: "page" pagePostType2: "single-page" __proto__: Object 1: event: "gtm.js" gtm.start: 1594382014744 gtm.uniqueEventId: 0 __proto__: Object 2: {event: "gtm.dom", gtm.uniqueEventId: 8} push: ƒ () length: 3 __proto__: Array(0) – Josef Moucachen Jul 10 '20 at 11:54

1 Answers1

0

To access object from Google Tag Manager you have to substitute the square brackets with dots. So classic JavaScript Array[0].name becomes Array.0.name.

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.

https://www.simoahava.com/gtm-tips/access-array-members-in-the-data-layer/

Michele Pisani
  • 13,567
  • 3
  • 25
  • 42