Unlike Adobe Launch or Tealium, the Google Tag Manager uses a nested dataLayer Object to structure its content. Since I kinda “grow up” with GTM, I am totally used to that. But recently I had within a client project a use case where I preferred to use a flat dataLayer.
A flat dataLayer can esp. help you with custom JavaScripts while not using GTM variables. The GTM variables are already working as a flat dataLayer object anyway.
The following code snippet will make the dataLayer flat.
Important: duplicate keys will be overwritten with the latest one. This is actually the key feature here, but important to know and understand.
function flat_dataLayer(ob)
{
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object') {
var flatObject = flat_dataLayer(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
flat_dataLayer(window.dataLayer);
Thanks Mate. This is what I was looking for! 🙂