在 Google Tag Manager With Javascript 中将数组变量转换为另一个用逗号分隔值的变量

Convert array variable into another variable with comma separated values in Google Tag Manager With Javascript

我正在尝试将数组格式的数据层变量转换为另一个应具有逗号分隔值的变量。

我有这样的数组格式:-

var data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  },]

我正在尝试将其转换为逗号分隔值,如下所示。

Product1: "productname",
Product1Price: 0.00,
Product1id: "1356",
Product1brand: "health", 
Product1stocklevel: "20",
Product2: "productname2",
Product2price: 0,
Product2id: "5263",
Product2brand: "hair",
Product2stocklevel: "",

这是我试过的 javascript 函数:-

data.map((e, i) => {
return Object.keys(e).map(p => `Product${i+1}${p=="name"?"":p}:"${e[p]}"`).join(",\n")}).join(",\n")

有了这个功能,我可以轻松得到我想要的东西。

但不知何故每当我试图将这个函数放入 gtm 变量(这是自定义 javascript 变量)

然后我在相同的变量上遇到了一些问题,如下所示:-

Error at line 7, character 14: This language feature is only supported for ECMASCRIPT_2015 mode or better: template literal.

自定义 javascript 变量中的实际代码在这里。

    function(){
data = {{Custom.orderData.items}};
 var dataByComa  = ''
 var Values = data.map(function (p, i) { return Object.keys (data[i]).map (function (k) { return Product ${p.position} ${k}: ${JSON.stringify(data[i][k])}`;});}).map(function (v) { return v.join(",\n"); }); 
var commaValues = Values.join(",\n"); 
return commaValues;
}
    


//Custom.orderData.items is datalayer variable which contains data in array format.

所以问题是为什么上面的函数在 gtm 中不起作用并给出一些错误。 您的帮助将不胜感激。谢谢:)

试试这个简单的循环

const data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  }]
  
  let dataByComa = '';

data.forEach((d, i)=> {
  Object.keys(d).forEach((key)=> {
    dataByComa += `product${i+1}_${key}=${d[key]}, \n`
  });
})
console.log(dataByComa)

错误完全是因为箭头函数只能与 ECMAScript 15 及更高版本一起使用。它与 Google Tag Manager.

无关

var data = [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health",
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair",
  },
];

const commaValues = data
  .map(function (p, i) {
    return Object.keys(data[i]).map(function (k) {
      return "Product" + p.position + k + ": " + JSON.stringify(data[i][k]);
    });
  })
  .map(function (v) {
    return v.join(",\n");
  });

console.log(commaValues.join(",\n"));