Suppose I have a data layer in my page. Suppose that data layer contains an array, like so:
var dataLayer = { "page": { "pageInfo": { "pageName": "Photos", "author": "Jan Exner", "breadCrumbs": ["home","photos"] } } };
Suppose I needed a Data Element that gives me the first element of my bread crumb list.
Wrong
The naive approach would be to make a Data Element that directly accesses a JS object, like so:
It has to do with the way DTM accesses data in the DOM — it essentially traverses the path and ultimately accesses the last bit of it using array notation.
So how do we do it, then? DTM is flexible, right? There must be a way, right?
Right
Yes, there is!
Instead of just accessing a JS object, we use custom script, like so:
Thank you so much Jan. I had been struggling with this for a few hours before a colleague sent across this post. You posted it today too! just in time 😀
LikeLike
Spooky 😉
LikeLike
In a similar manner, in the Data Element custom code you could do “return dataLayer.page.pageInfo.breadCrumb” (which returns your array), then call it with “_satellite.getVar(‘Breadcrumb’)[0]”. That way you can easily access any of the array values using just a single Data Element by changing the number in the call. I also use the same method to store objects, then call them with “_satellite.getVar(‘Page Info’)[‘author’] to get values for specific keys. I use this method to store a few arrays and objects I use frequently but which aren’t part of the data layer supplied by the developers; kind of my own DTM supplied data layer.
LikeLike
Very nice!
Thank you for sharing!
LikeLike
I was wondering if you have tried to use a Data Element with JS Object type with the following syntax instead:
dataLayer.page.pageInfo.breadCrumb.0
It should work too and looks simpler 🙂
LikeLike
Hi Andrey,
Don’t think that works, though. I’m getting “
Uncaught SyntaxError: Unexpected number(…)
” in Chrome.Pity, it looked nice and easy.
Cheers,
Jan
LikeLike
Legend.
Thanks, Jan – this issue was really starting to frustrate me. Your blog is a great resource.
Cheers, Rik
LikeLike
Thanks for the praise, Rik. Glad it helped!
LikeLike
Just dropping in 5 years later to thank you for the solution!
LikeLiked by 1 person