自定义 JS 变量来计算购物车中的商品数量

时间:2021-03-22 07:14:57

标签: javascript google-tag-manager enhanced-ecommerce

我的网站在购买时将以下数据推送到数据层

  ecommerce: {
    checkout: {
      actionField: {step: 3, revenue: null},
      products: [
        {
          name: 'Product 1',
          id: 4616,
          price: 516,
          brand: 'Brand Name',
          category: 'Product Type',
          variant: 'Product Version',
          quantity: 1,
          position: 1,
          dimension1: 'Guest',
          dimension2: '',
          dimension3: '',
          metric1: 2
        },
        {
          name: 'Product 2',
          id: 4618,
          price: 400,
          brand: 'Brand Name',
          category: 'Product Type',
          variant: 'Product Version',
          quantity: 1,
          position: 2,
          dimension1: 'Guest',
          dimension2: '',
          dimension3: '',
          metric1: 4
        }
      ]
    }
  }

我想将购物车中的商品数量作为标签管理器中的变量(即购物车中有 2 件商品)。 我正在尝试从这里调整 Dinesh's 解决方案,该解决方案对总金额做了类似的事情,但对我不起作用:

function(){
  var productList = ecommerce.checkout.products;
  var totalItems = 0;
  for(var i = 0;i<productList.length;i++)
  {
    totalItems+=(productList[i].quantity);
  }
  return totalItems;
}

不确定我做错了什么。

1 个答案:

答案 0 :(得分:0)

你已经有了答案,只需在for循环中找到你已经在做的产品的长度,即篮子里的产品数量。

希望我回答了你的问题