Home > Mobile >  Loop throug datalayer array for purchased products
Loop throug datalayer array for purchased products

Time:04-13

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(',');
}

CodePudding user response:

Function f can be replaced with the following:

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

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

CodePudding user response:

You can simply achieve that by a single line of code by using Array.map() method.

Try this :

const products = [
  {
    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
  }
];

const res = products.map((obj) => `${obj.id}_${obj.variant}`);

console.log(res.join(', '));

  • Related