I am web analyst for an ecommerce store and I haven't got access to code. All I can use is Tag Manager (GTM) which allows me to use custom JS code. I need to transform a JavaScript "cart" object so that it matches a syntax required by Google Analytics 4. In this example there are 2 items in the cart. There is a dataLayer for Adobe Analytics on the page, which has the following structure:
cart {
"itemNo": ["14347941","14508712"],
"itemQuant": [1,1],
"itemPrice": ["2,180.33","28.93"],
"uniqItemCount": 2,
"totItemCount": 2
}
I need it to look this way:
items[
{
item_id: "14347941",
quantity: 1,
price: 2180.33
},
{
item_id: "14508712",
quantity: 1,
price: 28.93
}
]
Every product is a separate object in an array of items. Additional difficulty: I can only use ES5, as ES6+ is not supported by GTM, so not let and const keywords etc.
Thanks for any help or suggestion.
You can use map
with a callback function
which is supported in ES5:
var cart = {
"itemNo": ["14347941","14508712"],
"itemQuant": [1,1],
"itemPrice": ["2,180.33","28.93"],
"uniqItemCount": 2,
"totItemCount": 2
}
var items = cart.itemNo.map(function (item_id, i) {
return {
item_id: item_id,
quantity: cart.itemQuant[i],
price: +cart.itemPrice[i].replace(/,/g, "")
};
});
console.log(items);
The call to replace
is used to remove the thousand separator(s) from the price strings, and +
is the unary plus operator to convert the string to a number type.