I am trying to convert datalayer variable which is in array format into another variable which should have comma separated values.
I have array format like this:-
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"
},]
Which is i am trying to convert into comma separated values like below.
Product1: "productname",
Product1Price: 0.00,
Product1id: "1356",
Product1brand: "health",
Product1stocklevel: "20",
Product2: "productname2",
Product2price: 0,
Product2id: "5263",
Product2brand: "hair",
Product2stocklevel: "",
Here is what I have tried javascript function :-
data.map((e, i) => {
return Object.keys(e).map(p => `Product${i+1}${p=="name"?"":p}:"${e[p]}"`).join(",\n")}).join(",\n")
With this function i can easily able to get what i want.
But somehow whenever i tried to put this function into gtm variable ( which is custom javascript variable )
Then i am facing some issue at same variable as below :-
Error at line 7, character 14: This language feature is only supported for ECMASCRIPT_2015 mode or better: template literal.
The actual code in custom javascript variable is here.
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.
So the question is why this above function is not working in gtm and giving some error. Your help will be appreciated. Thank you :)
The error is solely because arrow functions can only be used with ECMAScript 15 onwards. It has no relation to 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"));