Reputation: 23
I'm trying to calculate the value of the shopping cart based on data contianed in the GTM datalayer ecommerce object. I'm bringing the entire ecommerce object into a datalayer variable so I can work with it in the custom js variable, but I'm unable to make the recursive calculation work.
Here's an example of code from the datalayer:
{
"event": "checkout",
"ecommerce": {
"checkout": {
"products": [
{
"name": "coat",
"id": "14M",
"quantity": 1,
"price": "100.00"
},
{
"name": "pants",
"id": "12L",
"quantity": 3,
"price": "50.00"
}
]
}
}
}`
My goal is to identifies the number of products in the product array and then perform the calculation of products price * product quantity as many times as is required to go through the whol product array. In this case, it would be something like this:
(1*100) + (3*50) = 250.
I've tried modifying the code from Simo Ahava's related blogpost without success. The differences between his blogpost and my intention are:
Thanks in advance.
Upvotes: 2
Views: 4473
Reputation: 577
Since you have already created {{ecommerce}} variable , then it is very easy to fetch total amount on the basis of product's quantity and product's price.
You have to create on custom js variable Order Subtotal then in that custom js box paste below code
function(){
var productList={{ecommerce}}.checkout.products;
var totalAmount=0;
for(var i=0;i<productList.length;i++)
{
totalAmount+=(productList[i].quantity)*(parseFloat(productList[i].price));
}
return totalAmount;
}
I hope this will help you resolve you issue
Upvotes: 3
Reputation: 8736
This JS function will take latest datalayer ecommerce event and calculate product sum:
function productSum() {
var result = 0;
var ecommerceDataLayers = dataLayer.filter(function(e){return e.event == "checkout";});
if (ecommerceDataLayers.length)
{
var lastEcommerce = ecommerceDataLayers[ecommerceDataLayers.length-1];
for(i=0;i<lastEcommerce.ecommerce.checkout.products.length;i++) {
var product = lastEcommerce.ecommerce.checkout.products[i];
result += product.quantity*parseFloat(product.price);
}
}
return result;
}
Upvotes: 1