Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda