Can I set properties on google Datalayer object without using .push?

399 views Asked by At

Google Datalayer documentation Recommend that data be pushed onto the object. But I am wondering if I overwrite existing properties or set new ones on the object in scripts would be considered valid and be properly evaluated. For example, my homepage loads and in the head I have:

<script>window.datalayer = window.datalayer || []; 
datalayer.push({'event': 'my event'}); </script>

Then in a subsequent script I use lodash set in the following manner:

  <script>_.set(window.datalayer,'0.page.pageType', "someType"); </script>

which change the datalayer object to:

{
  "event": "my event",
  "page": {
    "pageType": "someType"
   }
}

Will this be valid? will the information be properly communicated to google platform.

1

There are 1 answers

0
XTOTHEL On

The dataLayer is actually an array of objects that keeps the HISTORY OF CHANGES to the data. So when you do dataLayer.push() you're actually adding an extra element to this history.

So technically can you keep track of all the parameters and mimic the same result, but the code as presented won't work.

Example object from the array:

event: "gtm.timer"
gtm.timerCurrentTime: 1602085776920
gtm.timerElapsedTime: 30004
gtm.timerEventNumber: 1
gtm.timerId: 99
gtm.timerInterval: 30000
gtm.timerLimit: 10
gtm.timerStartTime: 1602085746916
gtm.triggers: "440772_256"
gtm.uniqueEventId: 286