Why is GTM merging object values in dataLayer?
I have the following code:
dataLayer.push({event: 'A',eventAttributes: { attrA: 'a' }});
dataLayer.push({event: 'B',eventAttributes: { attrB: 'b' }});
dataLayer.push({event: 'C',eventAttributes: { attrC: 'c' }});
and a completely empty GTM container (no tags, no triggers, no variables).
When I inspect the Data Layer
tab of the GTM debug, I see this:
{
gtm: {start: 1448552543040, uniqueEventId: 1448552543091},
event: 'A',
eventAttributes: {attrA: 'a'}
}
{
gtm: {start: 1448552543040, uniqueEventId: 1448552543092},
event: 'B',
eventAttributes: {attrA: 'a', attrB: 'b'}
}
{
gtm: {start: 1448552543040, uniqueEventId: 1448552543092},
event: 'C',
eventAttributes: {attrA: 'a', attrB: 'b', attrC: 'C'}
}
As you can see GTM is merging values to the eventAttributes
object instead of overwriting the object.
Q1: Why is GTM doing this?
Q2: Is there a way I can prevent this from happening (apart from defining each object property as a separate variable)?
FYI I'm using the eventAttributes
object in the Data Layer because I want to then simply re-use whatever is in it as attributes for my event-based tools (Mixpanel, KISSmetrics...). With the above issue, I just don't see any way to scale GTM implementations for Mixpanel/KISSmetrics if I have to explicitly declare all variables in the DataLayer and GTM.
UPDATE
After reviewing the dataLayer in the console itself, it appears the values are properly pushed and not merged:
So it must be when reading the dataLayer that GTM decides to merge them!
Answer to Q1:
GTM is doing this because this is the behaviour of the DataLayer as intended: https://github.com/google/data-layer-helper
Adding Q2 answer from Kitravee Siwatkittisuk to make this post exhaustive:
Answer to Q2:
set _clear to true to preventing default recursive merge
dataLayer.push({items: [1], _clear: true})
Answer to Q2:
set _clear to true to preventing default recursive merge
dataLayer.push({items: [1], _clear: true})