Push multiple objects into the dataLayer

66 Views Asked by At

I have the following javascript function that pushes 1 object made of 5 key values into the dataLayer.

function pollForDatalayer() {
  if (typeof(dataLayer.push) === 'function') {
  // The dataLayer.push function is defined, so you can run it here
    for (var i = 0; i < campaigns.length; i++) {
      var campaign = campaigns[i];
      dataLayer.push({
        'event': 'xxx',
        'event_category': 'xxx',
        'campaignName': campaign.key,
        'experienceName': campaign.split,
        'campaignID': campaign.variant_id
        });
    }
    console.log("Data Layer Found.");
  } else {
     console.log("polling for Data Layer.");
    setTimeout(pollForDatalayer, 5000);  
  }
}
pollForDatalayer();

How do I make sure I can push multiple arrays into the dataLayer? Right now if I have 2 or more objects information to store into the dataLayer only the last one is being pushed. Not the first one.

example of end result of data pushed into the dataLayer I would like to obtain:

{
    "event": "xxx",
    "event_category": "xxx",
    "campaignName": "TEST-1",
    "experienceName": "xxx",
    "campaignID": xxx,
    "gtm.uniqueEventId": xxx
},
{
    "event": "xxx",
    "event_category": "xxx",
    "campaignName": "TEST-2",
    "experienceName": "xxx",
    "campaignID": xxx,
    "gtm.uniqueEventId": xxx
}
1

There are 1 best solutions below

0
On

If I understood the question correctly, it can be done like this

function pollForDatalayer() {
  if (typeof dataLayer.push === 'function') {
    var dataToPush = [];

    for (var i = 0; i < campaigns.length; i++) {
      var campaign = campaigns[i];
      var dataObject = {
        event: 'xxx',
        event_category: 'xxx',
        campaignName: campaign.key,
        experienceName: campaign.split,
        campaignID: campaign.variant_id,
      };
    
      dataToPush.push(dataObject);
    }

    dataLayer.push.apply(dataLayer, dataToPush);
    console.log('Data Layer Found.');
  } else {
    console.log('polling for Data Layer.');
    setTimeout(pollForDatalayer, 5000);
  }
}
pollForDatalayer();