如何使用不带箭头函数的 javascript 将此 javascript 对象转换为数组?

How do I convert this javascript object into an array using javascript without arrow functions?

这是通过 GTM 作为 object 传递的,我必须将其转换为 array,以便循环遍历它。

我已经为它写了一个 forEach 声明,但我似乎无法正确格式化它以使其工作。

(完全公开,我不是开发人员,我只是想在 GTM 中蒙混过关)

我试过使用 Object.entries(obj),但结果是多个 arrays

{
  0: {
    category_id: '',
    cart_entry_id: 0,
    quantity: 3,
    product_id: '678294',
    unit_price: 5.29,
    product_name: 'Office Depot® Brand 8-Pocket Poly Organizer, Assorted Colors (No Color Choice)',
  },
  2: {
    category_id: '543867',
    cart_entry_id: 2,
    quantity: 1,
    product_id: '448906',
    unit_price: 34.99,
    product_name: 'Realspace® All-Pile Studded Chair Mat, 36" x 48";, Clear',
  },
  3: {
    category_id: '543867',
    cart_entry_id: 3,
    quantity: 1,
    product_id: '493876',
    unit_price: 179.99,
    product_name: 'Realspace® MFTC 200 Mesh Multifunction Ergonomic Mid-Back Task Chair, Black',
  }
}

假设这个对象是您已经拥有的东西并且您的问题包含该对象的打印输出。

for(var i in json_data)
   result.push([i, json_data [i]]);

check out this question for a more through answer.

如果你有这样的对象:

{
  0: 'some data',
  1: 'some data',
  2: 'some data'
}

你可以很容易地把它变成一个数组:

const input = {
  0: 'some data',
  1: 'some data',
  2: 'some data'
};

const output = Object.values(input);

console.log(output);

如果您需要确保键总是以相同的顺序(您可能应该这样做),您可以先对其进行排序。

const input = {
  0: 'some data',
  1: 'some data',
  2: 'some data'
};

// entries turns the object into an array of arrays with each
// entry being [key, value].
const output = Object.entries(input)
  .sort((a, b) => a[0] - b[0])
  .map(i => i[1]);

console.log(output);

由于您询问时没有使用数组函数,只需将箭头函数更改为非箭头函数即可(尽管不确定您为什么要这样做):

const input = {
  0: 'some data',
  1: 'some data',
  2: 'some data'
};

// entries turns the object into an array of arrays with each
// entry being [key, value].
const output = Object.entries(input)
  .sort(function (a, b) { return a[0] - b[0] })
  .map(function (i) { return i[1] });

console.log(output);

假设您对象是来自 dataLayer 的电子商务交易(但可以是购物车或任何其他)对象,并且您希望将其转换为数组。

  1. 将电子商务对象设置为 DL 变量

DL variable: ecommerce.purchase object

所以它看起来像这样: GTM debugger: ecommerce object

2] 使用自定义 JS 变量将其转换为数组:

function(){
  var a = JSON.stringify({{DL EE purchase array}});
  return a;
}

这会将 ecommerce.purchase 从对象转换为数组 [字符串数据类型]。