Search code examples
javascriptarraysgoogle-tag-manager

Loop throug datalayer array for purchased products


I have a datalayer purchase object with two products (but user can buy more products):

This is an array I have:

[
  {
    name: "Product1",
    id: 5986,
    price: 980,
    brand: "brand1",
    category: "Cable & Adapter",
    quantity: 1,
    dimension51: "",
    dimension52: "In Stock",
    metric11: 980,
    variant: 5771
  },
  {
    name: "Prooduct2",
    id: 5987,
    price: 980,
    brand: "brand2",
    category: "Cable & Adapter",
    quantity: 1,
    dimension51: "",
    dimension52: "In Stock",
    metric11: 980,
    variant: 5770
  }
]

I want to create a JS function that would concatenate from each product ProductID and VariantID and it will return a list of productid_variantid.

I would like to via js the following:

5986_5771, 5987_5770

I have already this JS but it is returning undefined in Google Tag Manager.

function f(){
    var p = {{dataLayer.ecommerce.purchase.products}};
    var result = [];

    for(var i=0;i<p.length;i++){
        result.push(p[i].id.concat('_',p[i].variant));
    }

    return result.join(',');
}


Solution

  • Function f can be replaced with the following:

    ES6:

    function f(){
      var p = {{dataLayer.ecommerce.purchase.products}};
      return p.map(({id, variant}) => `${id}_${variant}`).join(',');
    }
    

    ES5:

    function f(){
      var p = {{dataLayer.ecommerce.purchase.products}};
      const results = [];
      for (let i = 0; i < p.length; i++) {
        const product = p[i];
        const resultString = p[i].id + '_' + p[i].variant;
        results.push(resultString);
      }
      return results.join(',');
    }
    

    (The {{dataLayer.ecommerce.purchase.products}} syntax in your example is not valid in JavaScript, however I trust that this line works for you)