0

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.

1
  • When are you invoking this custom JS variable? It should be on the "promoImp" event. Commented Feb 21, 2017 at 15:44

1 Answer 1

3

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:

enter image description here

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.

Sign up to request clarification or add additional context in comments.

2 Comments

function () { return Object.keys({{Promotions}}).splice(0, 3); } This code solved my issue. Thank you for the help
Do you know why my promotions variable is undefined when running this code? I defined it as a data layer variable, but I get an undefined value. I am unsure what I am doing wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.