How I do 'for loop' inside Array then add to DataLayer.push

855 Views Asked by At

I have retrieve IDs data from webpage as Custom Javascript Variable:

function() {

    var productID = document.querySelectorAll('a[data-productID]');

    var allproductID = Array.prototype.map.call(productID, function(a) {
        return a.getAttribute('data-productID');
    });

    return allproductID;

}

and this function retrun all ids in page, that's good.

But now i need to send these ids to google via Tag Manager,

What i'm looking for is how i can loop inside these return array and put values from Array to 'id' and push that to Google, final result must be like:

<script>
gtag('event','view_item', {
  value: 'somevalue'
  'items': [
    {
      'id': 1234, 
      'google_business_vertical': 'retail'
    },
    {
      'id': 45678, 
      'google_business_vertical': 'retail'
    }
  ]
});
</script>

Thank you

1

There are 1 best solutions below

2
On BEST ANSWER

You can create the object in the array by the return statement and than you can add to the secend return the push like

 function() {

var productID = document.querySelectorAll('a[data-productID]');

var allproductID = Array.prototype.map.call(productID, function(a) {
    return  {
              'id':  a.getAttribute('data-productID'), 
              'google_business_vertical': 'retail'
            }
});



return dataLayer.push({
          'event': 'view_items',
          'value': 'somevalue',
          'items' : allproductID
        });
}