Reputation: 23
I need help for writing custom javascript in data layer. I am trying to get names.
promotionImpression:
{
event: 'promoImp',
ecommerce: {
promoView: {
promotions: {
142398:{
id: '142398',
name: 'sadr'
},
142312:{
id: '142312',
name: 'qas'
}
}
}
} },gtm.uniqueEventId: 470
I have tried this javascript but it returns undefined. When I tried this locally it returns names perfectly.
function() {
var names = [];
for (promotion in ecommerce.promoView.promotions) {
names.push(ecommerce.promoView.promotions[promotion].name);
}
return names.join(); }
Can anybody help on this. Thanks in advance.
Upvotes: 0
Views: 1624
Reputation: 32780
I guess you are trying to access the dataLayer directly from within your custom function. However the dataLayer is not a (JSON) object, it is an array of objects. So you cannot address the ecommerce data via dot notation, you'd need to give the index of the dataLayer array element:
dataLayer[index].ecommerce.promoView.promotions
where "index" is the index of the dataLayer element that contains the ecommerce data. Now clearly that would suck (especially since the index might not always be the same, depending on what you pushed in which order to the dataLayer), so there is a better way.
In it's internal data model (the inescapable Simo Ahava has written a lot about this) GTM flattens the dataLayer elements into a single object. You would not access this data model directly, instead use a variable of the dataLayer type:
Now use that in your custom function:
function() {
var names = [];
for (promotion in promotions) {
names.push(promotions[promotion].name);
}
return names.join();
}
Not properly tested, so the function might need a tweak, but basically that would be the way to go.
Upvotes: 3