0

I would like to know the correct function for Google Tag Manager, when you create a Custom JavaScript, how can I get the product "id"("259496742","1061024") when you have an array.

 {
       "0": "event",
       "1": "purchase",
       "2": {
          "transaction_id": "ORD00174",
          "affiliation": "Lightspeed",
          "value": "0.00",
          "currency": "EUR",
          "tax": "0.00",
          "shipping": "0.00",
          "items": [
             {
                "id": 259496742,
                "name": "Haarklem Print",
                "currency": "EUR",
                "brand": "",
                "variant": 259496742,
                "price": "9.95",
                "quantity": 1
             },
             {
                "id": 1061024,
                "name": "Lila Hoed",
                "currency": "EUR",
                "brand": "",
                "variant": 263376478,
                "price": "19.95",
                "quantity": 1
             }
          ],
EmLa
  • 1
  • 1

1 Answers1

1

You can do:

const obj = {
   "0": "event",
   "1": "purchase",
   "2": {
      "transaction_id": "ORD00174",
      "affiliation": "Lightspeed",
      "value": "0.00",
      "currency": "EUR",
      "tax": "0.00",
      "shipping": "0.00",
      "items": [
         {
            "id": 259496742,
            "name": "Haarklem Print",
            "currency": "EUR",
            "brand": "",
            "variant": 259496742,
            "price": "9.95",
            "quantity": 1
         },
         {
            "id": "1061024",
            "name": "Lila Hoed",
            "currency": "EUR",
            "brand": "",
            "variant": 263376478,
            "price": "19.95",
            "quantity": 1
         }
      ],
   }
}


// This is the funciton you need
function getIds(obj) {
  let ids = []

  for(const key in obj) {
    const currentValue = obj[key]
    if (Object.prototype.hasOwnProperty.call(currentValue, 'items')) {
      ids = [...ids, ...currentValue.items.map(item => item.id)]
    }
  }

  return ids
}
///


//Just to show the result do not copy this
console.log(getIds(obj))
Toni Bardina Comas
  • 1,670
  • 1
  • 5
  • 15
  • If I go to the console, definitely I get the ids values, however when I create the Custom JavaScript in GTM I get an error. Do you know how to proper implement it in GTM? Thank you for your help – EmLa Jul 04 '22 at 13:12
  • The javaScript must define a function with a return value. – EmLa Jul 25 '22 at 13:55