Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda