You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GTM中基于dataLayer生成指定格式的商品名称对象数组

GTM 实现方案代码

你可以直接使用如下JavaScript代码,适配GTM运行环境:

// 适配GTM原生dataLayer(数组结构)的取值逻辑
const products = dataLayer.find(item => item && item.products)?.products || [];

// 如果你是自行赋值的dataLayer对象结构,可替换上一行为:
// const products = dataLayer.products || [];

// 生成目标格式数组
const formattedProducts = products.map((prod, idx) => {
  return {
    [`product${idx + 1}`]: prod.name
  }
})

// GTM自定义JS变量中直接返回即可:return formattedProducts
console.log(JSON.stringify(formattedProducts))

代码说明

  • 取值逻辑做了兜底兼容,不存在products数据时会返回空数组,不会出现运行报错导致GTM加载异常
  • 遍历数组时用索引+1生成product1、product2这类动态键,直接取商品name属性作为值,输出完全符合要求的结构
  • 运行后输出结果为:
    [{"product1":"Protein Corn Muffin"},{"product2":"Salted Caramel Super Smoothie"},{"product3":"Pop Corn"},{"product4":"Fruit Pops!"}]

内容的提问来源于stack exchange,提问作者Kanchan Jha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:48:04