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:
- I don't need to set the cart value as an ecommerce Custom Metric. I want to just return the value of the cart in the custom js.
- I don't want this to involve adding or deleting items from the cart. Instead, I just want to calculate the value when the GTM Event "checkout" is triggered and calculate the value of the contained products.
Thanks in advance.
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
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;
}
来源:https://stackoverflow.com/questions/45557541/google-tag-manager-custom-javascript-variable-based-on-ecommerce-datalayer-objec