'Having trouble pushing dynamic key-value pairs to the data layer using Google Tag Manager

I'm trying to collect and fire form fields as dataLayer variables using Google Tag Manager:

<script>
  
  var fields = [];
  var fields = document.querySelectorAll("input");  
  
  var x = fields.forEach(function(field) {
    var obj = {};
    var a = field.getAttribute("name");
    var b = field.value;
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      obj[a] = b
    });
  }); 
  
</script>

My intention is, when triggered, to:

  1. Collect all of the form values in fields
  2. Iterate over the array of items and get the field's name and value
  3. Fire the name and value as a key-value pair
  4. Return to iterate over the next item.

However, I'm receiving the error:

Error at line 12, character 10: Parse error. '}' expected

And no matter what changes I make, I can't seem to properly trouble shoot.



Solution 1:[1]

You can't have a = in the push function. You can change your code slightly. Do the assignment before pushing like obj[a] = b, and then push the object in dataLayer at each iteration.


Working code logic below

var fields = [];
var fields = document.querySelectorAll("input");

var x = fields.forEach(function(field) {
  var obj = {};
  var a = field.getAttribute("name");
  var b = field.value;
  obj[a] = b;
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push(obj);
});

console.log(dataLayer)
<input name='a' value='a' />
<input name='b' value='b' />
<input name='c' value='c' />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tushar