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

时间:2019-10-03 19:15:05

标签: javascript arrays google-tag-manager

这是通过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',
  }
}

3 个答案:

答案 0 :(得分:0)

假设该对象已经存在,并且您的问题中包含该对象的打印输出。

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

check out this question for a more through answer.

答案 1 :(得分:0)

如果您只有这样的对象:

{
  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);

答案 2 :(得分:0)

假设您的对象是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从对象转换为数组[string数据类型]。

相关问题