在Google Tag Manager中修改数组键名适配GA4电商跟踪
解决GTM中GA4电商跟踪变量转换后值为undefined的问题
问题分析
直接修改{{transactionProducts}}返回的原对象时,可能因该对象属性被GTM做了访问限制(比如不可写、只读),导致赋值操作无法正确读取原属性值,最终新键对应值为undefined。
修复方案
不要直接修改原数组内的对象,而是创建新对象映射GA4所需字段,避开原对象的属性限制,同时完全符合ES5语法要求:
function() { var originalProducts = {{transactionProducts}}; var ga4Products = []; originalProducts.forEach(function(product) { var newProduct = {}; // 映射GA4字段,仅当原属性存在时赋值 if (product.sku) newProduct.item_id = product.sku; if (product.name) newProduct.item_name = product.name; if (product.category) newProduct.item_category = product.category; // 如有其他需转换的字段,继续在此添加映射逻辑 ga4Products.push(newProduct); }); return ga4Products; }
关键说明
- 通过创建新对象的方式,规避GTM对原对象的属性访问限制
- 增加
if判断过滤不存在的原属性,避免生成无意义的undefined字段 - 全程使用ES5语法,适配GTM的运行环境
内容的提问来源于stack exchange,提问作者applesInGtm
相关产品推荐
相关产品推荐

