Array
Intermediate

Get a specific variable from an array of objects

The macro needs an array of object as input. My suggestion is that you get array as a datalayer variable in your website. It picks the assigned variable (in this case ‘id’) and outputs it again like an array: [ ‘123’, ‘456’ ].

Usecase

This is used commonly for ecommerce websites. The information about multiple products is pushed as an array into the datalayer. You want to filter it to send to ViewContent or Purchase tags for example. This macro helps you.

Instructions

  • Replace the {{var_products_array}} by a GTM variable, which contains an array of information.
  • Replace ‘id’ in line 28 with the variable name, which is inside the array.
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.

Isn’t this the macro you were looking for? Check-out related macro’s below or request one.

Related macros

All macro’s

Capture UTM parameters and save them into separate cookies

Array
Intermediate

Capture UTM parameters

Array
Intermediate

Form field value

Array
Intermediate