Search code examples
google-tag-managergoogle-datalayer

How to create GTM data layer variable with complex array


In Google Tag Manager a pre-defined variable type of "Data Layer Variable" exists with an input for the variable name. In a standard single level of key/value pairs this is easy.

var dataLayer = [{"mykey":"myvalue"}];

Given that data layer you'd just use mykey as your variable to input into GTM. However, if you use the CEDDL spec (http://www.w3.org/2013/12/ceddl-201312.pdf) structure you end up with a deeply nested array:

dataLayer = [
  {
    "product": [
      {
        "category": {
          "primaryCategory": "Auto Loans"
        },
        "productInfo": {
          "productID": "1",
          "productName": "PurchaseLoan",
          "description": "Auto finance loan"
        },
        "security": [
          "Analytics",
          "Personalization",
          "Recommendations"
        ]
      }
    ]
  }
]

So the real question is: how do I access the value of "productName" in the above example?

In standard Javascript you might access it like so: dataLayer[1].product[0].productInfo.productName or dataLayer.1.product.1.productInfo.productName

... but neither of these options work (with or without dataLayer.1 as the first node).

This is the UI to enter the variable name: enter image description here


Solution

  • When you define your DataLayer variable in GTM, you don't need to specify "dataLayer" in the variable name, ie. it should just be:

    product.0.productInfo.productName