Avishek Basu Mallick Avishek Basu Mallick - 5 months ago 40
jQuery Question

For Loop not working in custom javascript variable for Google Tag Manager

My website does not have a data layer and I am trying to scrape the DOM element to pass some data to a custom Javascript variable. I am a newbie to both HTML and Javascript and hence I seem to be making a mistake.

The For loop for multiple products is not working - I am getting an error - "Error at line 17, character 16: Parse error. '{' expected"

This is my code:

function() {
var a = document.querySelectorAll("p.product-name");
var b = document.querySelectorAll("small.cart_ref");
var c = document.querySelectorAll("input.cart_quantity_input.form-control.grey");
var d = document.querySelectorAll("li.price");
var ecommerceData = {
'ecommerce': {
'purchase': {
'actionField': {
'id': {{Random Number}}, // Transaction ID. Dummy
'revenue': {{Revenue}}, // Total transaction value (incl. tax and shipping)
'shipping': {{Shipping}}
},
'products': [
for (var i = 0; i < b.length; i++) {
'name': a[i+1].innerHTML,
'id': b[i].innerHTML,
'quantity': c[i].innerHTML,
'price': d[i].innerHTML
},
]
}
};
return ecommerceData;
}


If I use the code without the For loop, it works:

function() {
var a = document.querySelectorAll("p.product-name");
var b = document.querySelectorAll("small.cart_ref");
var c = document.querySelectorAll("input.cart_quantity_input.form-control.grey")
var d = document.querySelectorAll("li.price");
var e = c.value;
var ecommerceData = {
'ecommerce': {
'purchase': {
'actionField': {
'id': {{Random Number}}, // Transaction ID. Dummy
'revenue': {{Revenue}}, // Total transaction value (incl. tax and shipping)
'shipping': {{Shipping}}
},
'products': [
{
{'name': a[1].innerHTML,
'id': b[0].innerHTML,
'quantity': e[0].innerHTML,
'price': d[0].innerHTML
}
]
}
}
};
return ecommerceData;
}


The order transaction page is www.decathlon.in/order.

Answer

You can't insert a loop in an object literal

Create the products array separately.

var products = [];
for (var i = 0; i < b.length; i++) {
    var obj = {};
    obj.name = a[i+1].innerHTML;
    obj.id= b[i].innerHTML;
    obj.quantity= c[i].innerHTML;
    obj.price= d[i].innerHTML; 
    products.push(obj);
 }

Then add it to your object

'products': products