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

226
Vistas
Each data only appears 1 data, and when access each data the result is undefined

I have a product div which contains the data-product attribute, its value is object. And I want to put the product data into gtag.

but why when I do each, there is only 1 data? and when I want to access data.id and data.name why is it undefined?

$(document).ready(function(){
  const promotions = []
  
    $(".product-item").each(function(){
    const data = $(this).data('product');
    
    promotions.push({
      "id": data.id,
      "name": data.name
    })
  })
  
  //gtag('event', 'view_promotion', {
    //promotions
  //});
  
  $('.product-item').each(function(){
    $(this).on("click", function(e){
      const data = $(this).data('product')
      console.log(data)
    })
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-item" data-product='{"id" : 123, "name" : "Product 1"}'>
  Product 1
</div>
<div class="product-item" data-product='{"id" : 124, "name" : "Product 2"}'>
  Product 2
</div>
<div class="product-item" data-product='{"id" : 125, "name" : "Product 3"}'>
  Product 3
</div>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Change your HTML code, works for me:

<div class="product-item" data-product='{"id":124,"name":"Product 1"}'>
    Product 1
</div>
<div class="product-item" data-product='{"id":125,"name":"Product 2"}'>
    Product 2
</div>
<div class="product-item" data-product='{"id":126,"name":"Product 3"}'>
    Product 3
</div>
about 4 years ago · Juan Pablo Isaza Denunciar

0

As per the API the attribute value must be a valid JSON including quoted property names.

In your case it is not properly formatted as JSON hence, it is not working. Format your data-product as valid JSON.

Once the JSON is fixed, to loop over promotions

$(document).ready(function(){
  let promotions = []
  $(".product-item").each(function(){
    const data = $(this).data('product');
        
    promotions.push({
      "id": data.id,
      "name": data.name
    })
  })
      
           
  gtag('event', 'view_promotion', {
    promotions
  });
})
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