[英]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',
}
}
假设您已经拥有此 object,并且您的问题包含该 object 的打印输出。
for(var i in json_data)
result.push([i, json_data [i]]);
如果您只有这样的 object:
{
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);
假设您 object 是来自 dataLayer 的电子商务交易(但可以是购物车或任何其他)object,并且您希望将其转换为数组。
DL 变量:ecommerce.purchase object
所以它看起来像这样: GTM 调试器:电子商务 object
2] 使用自定义 JS 变量将其转换为数组:
function(){ var a = JSON.stringify({{DL EE purchase array}}); return a; }
这会将 ecommerce.purchase 从 object 转换为数组 [字符串数据类型]。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.