Ad

Return Array Without Quotes

- 1 answer

The scenario

I want to push product gtins to Google Merchant Center.

What I'm getting

"products": ['{"gtin":"5704378978422"}', '{"gtin":"5704378978057"}']

What I want to get

Without single quotes for each array member in the format:

"products": [{"gtin":"GTIN1"}, {"gtin":"GTIN2"}]

As described in step 3 here: https://support.google.com/merchants/answer/7519329

My Google Tag Manager setup

  1. I have created a Data Layer Variable {{DLV - ecommerce.purchase.products}} from ecommerce.purchase.products
  2. I have created a Custom Javascript variable with the following code:

Code:

function() {
  var products = {{DLV - ecommerce.purchase.products}};
  return products.reduce(function(arr, prod) { 
    return arr.concat("{" + '"' + "gtin" + '"' + ":" + '"' + prod.gtin + '"' + "}" ); }, []);
}

What would be the best way to do this

I'm new to JavaScript, and would appreciate any comments and suggestions

Ad

Answer

By using the concat function you are creating a string concatenation, not an object. You should probably use map instead of reduce. Like this:

function() {
  var products = {{DLV - ecommerce.purchase.products}};
  return products.map(function(prod) { 
    return {"gtin": prod.gtin};
  });
}
Ad
source: stackoverflow.com
Ad