循环遍历购买产品的数据层数组

Loop throug datalayer array for purchased 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
  }
]

我想创建一个 JS 函数,它将连接每个产品的 ProductID 和 VariantID,它将 return 一个 productid_variantid.[= 的列表12=]

我想通过 js 执行以下操作:

5986_5771,5987_5770

我已经有了这个 JS,但它在 Google 跟踪代码管理器中 returning 未定义

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

函数 f 可以替换为以下内容:

ES6:

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

ES5:

function f(){
  var p = {{dataLayer.ecommerce.purchase.products}};
  const results = [];
  for (let i = 0; i < p.length; i++) {
    const product = p[i];
    const resultString = p[i].id + '_' + p[i].variant;
    results.push(resultString);
  }
  return results.join(',');
}

(您示例中的 {{dataLayer.ecommerce.purchase.products}} 语法在 JavaScript 中无效,但我相信这一行适合您)

您可以使用 Array.map() 方法通过一行代码轻松实现。

试试这个:

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

根据作者评论更新(正常 forEach 循环):

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.forEach(function(obj) {
  res.push(`${obj.id}_${obj.variant}`);
}); 

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