我的问题可能很简单,但我的眼睛在眨,我现在想不出别的东西。任何帮助表示赞赏
这是我的初始数组
var Products = [
{
"order_product_id":"1111",
"order_id":"555",
"product_id":"111",
"name":"name1",
"model":"111",
"quantity":"1",
"price":"100",
"total":"100",
"tax":"20",
},
{
"order_product_id":"2222",
"order_id":"555",
"product_id":"222",
"name":"name2",
"model":"222",
"quantity":"1",
"price":"200",
"total":"200",
"tax":"40",
}
];
这是我需要的数组(更改名称并排除一些元素)
{
"id": "1111",
"name": "name1",
"category": "",
"list_position": 1,
"quantity": 1,
"price": '100'
},
{
"id": "2222",
"name": "name2",
"category": " ",
"list_position": 2,
"quantity": 1,
"price": '200'
}
最后这是我想在操作后放置新产品阵列的地方
{
"transaction_id": 1,
"value": 99,
"currency": "EUR",
"shipping": 0,
"items": Items
}
我试过 push/forEach/even string 但我无法像 Google 想要的那样得到一个最终的干净数组
gtag('event', 'purchase', {
"transaction_id": 1,
"value": 99,
"currency": "EUR",
"shipping": 0,
"items": [
{
"id": "1111",
"name": "name1",
"category": "",
"list_position": 1,
"quantity": 1,
"price": '100'
},
{
"id": "2222",
"name": "name2",
"category": " ",
"list_position": 2,
"quantity": 1,
"price": '200'
}
]
});
最佳答案
您可以创建自己的方法来构建对象并使用 Array.prototype.map
进行迭代。
var Products = [
{
order_product_id: "1111",
order_id: "555",
product_id: "111",
name: "name1",
model: "111",
quantity: "1",
price: "100",
total: "100",
tax: "20"
},
{
order_product_id: "2222",
order_id: "555",
product_id: "222",
name: "name2",
model: "222",
quantity: "1",
price: "200",
total: "200",
tax: "40"
}
];
let getObj = (obj, i) => ({
id: obj.order_product_id,
name: obj.name,
category: obj.category || "",
list_position: i + 1,
quantity: obj.quantity,
price: obj.price
});
let Items = Products.map(getObj);
console.log(Items);
关于javascript - 将对象数组转换为不同结构对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436126/