Search code examples
javascriptgoogle-tag-manager

How can I show the key and value of an object in Google Tagmanager?


I have an object stored in my LocalStorage with keys and values. I want to retrieve that object and put both the key and value in some HTML. I used this code and works fine in my console:

const object1 = {
  a: 'somestring',
  b: 42
};
for (const [key, value] of Object.entries(object1)) {
  
  console.log(`${key}: ${value}`);
}

Now I get multiple errors that the language feature is only supported for ECMASCRIPT_2015 mode or better. How can I fix this so that I can show the keys and corresponding value?


Solution

  • It actually is telling you to not use ES6 features. Yes, unfortunately, Google doesn't see its GTM product as a very important to their business, so they limit the resources spent on it severely.

    As a result, GTM doesn't support ES6, aka Ecma Script 2015. Yep, no support for new JS features like const, for..of, etc. You have to rewrite your code, like so:

    function(){
      var object1 = {
        a: 'somestring',
        b: 42
      };
      Object.keys(object1).forEach(function(key){
        console.log(key, object1[key]);
      })
      return "";
    }

    I wrapped it in a function to be used in a GTM var. If you meant it to be a CHTML tag (which I advice against), feel free to get rid of the wrapping function and return.