Reputation: 1
I am working on the Google Tag Manager implementation for an eCommerce website.
Unfortunately, we can't hard-code the DataLayers. Therefore I am looking at workarounds. I thought I could implement the datalayers myself using google tag manager and a custom javascript macro. I am now working on the purchase event. I successfully scraped the purchase confirmation page and I got three variables, productName, productId and productPrice. Which is all I need for the moment. These three variables come as arrays in the case when multiple products are purchased in the same transaction. So the variables look like the ones shown below.
Now my goal is to format this data in the datalayers format so it can be used in GTM and GA.
See my code below
Thanks for your help!
Jack
//this is what I currently have
var productName = [ 'Product A', 'Product B', 'Product C']
var productId = ['1111', '2222', '3333']
var productPrice = [2.99, 4.95, 6.95]
//this is the format I want to achieve
var products = [{
'name': 'Product A',
'id': '1111',
'price': '2.99'
},
{
'name': 'Product B',
'id': '2222',
'price': '4.95'
},
{
'name': 'Product C',
'id': '3333',
'price': '6.95'
}]
Upvotes: 0
Views: 349
Reputation: 89
This will work, but I'm not sure about support on all browsers
var column = ['name', 'id', 'price']
var productName = ['Product A', 'Product B', 'Product C']
var productId = ['1111', '2222', '3333']
var productPrice = [2.99, 4.95, 6.95]
var agg = [productName, productId, productPrice];
var row = Object.keys(agg[0])
.map(colNumber => agg.map(rowNumber => rowNumber[colNumber]))
var arr = row.map(function(row) {
return row.reduce(function(result, field, index) {
result[column[index]] = field;
return result;
}, {});
});
var products = arr.reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});
console.log(products)
Upvotes: 1