Search code examples
google-tag-managergoogle-datalayergoogle-optimize

dataLayer.push is adding a new item instead of updating an existing one


I'm running some A/B tests with Google Optimize and am trying to just update a value in the dataLayer from my app but instead of updating it, it just adds a new object to it. According to the docs it should update if the key already exists.

Am I missing something?

For example:

// initiate dataLayer at the top of <head>
window.dataLayer = [{
  message: ""
}];

// later after some stuff loaded
window.dataLayer.push({message: 'Test message'});

console.log(window.dataLayer) // added instead of updated
// [
//   {message: ""},
//   {message: "test"}
// ]

Solution

  • In short, and thanks to comment of @IskandarRezaRazali, it's working correctly but I should have been using window.google_tag_manager["GTM-XXXXXX"].dataLayer.get('message') (which will always give you the latest entry) to retrieve the value rather than trying to access it via index or having to do Array.find`.