Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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' />

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!