PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

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

 July 22, 2022     google-ads-script, google-datalayer, google-remarketing-audience, google-tag-manager, javascript     No comments   

Issue

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


Solution

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
        });
}


Answered By - Sebastian Offers
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing