Array
Intermediair

Een specifieke variabele ophalen uit een array van objecten

De macro heeft een array van objecten nodig als invoer. Onze suggestie is dat je array als een datalayer variabele in je website krijgt. Het pakt de toegewezen variabele (in dit geval ‘id’) en voert deze weer uit als een array: [ ‘123’, ‘456’ ].

Usecase

Dit wordt vaak gebruikt voor e-commerce websites. De informatie over meerdere producten wordt als een array in de datalayer geduwd. Je wilt deze filteren om bijvoorbeeld naar ViewContent of Purchase tags te sturen. Deze macro helpt je daarbij.

Instructies

  • Vervang de {{var_products_array}} door een GTM-variabele die een array met informatie bevat.
  • Vervang ‘id’ in regel 28 door de variabelenaam die in de array staat.
JavaScript

// Gets a specific variable from a array of objects
// Input example:
// [
//   {
//     id: "123",
//     name: "Swimwear blue",
//     brand: "006",
//     variant: "M",
//     price: "79",
//     quantity: "1",
//     list: "/collections/swimwear",
//   },
//   {
//     id: "456",
//     name: "Shorts grey",
//     brand: "009",
//     variant: "XL",
//     price: "79.0",
//     quantity: "1",
//     list: "/collections/shorts",
//   }
// ]
//
// Output example: [ '123', '456' ]

function() {
  var products = {{var_products_array}};
  return products.reduce(function(arr, prod) { return arr.concat(prod.id); }, []);
}

// Notice that 'id' can be replaced with for example 'name'.
// It depends on the contents of your array you want to pick.

Is dit niet de macro die je zocht? Bekijk alle macro’s die we op onze site hebben gezet of vraag er een aan.