I have a JavaScript object (Shopify.checkout.line_items) that contains an array. I want to fill out an array (items) with this data.
The below is a simplified version of the code with the core problem that you can't just shove a for loop in the middle of an array literal:
gtag('event', 'purchase', {
'transaction_id': '{{ order.order_number }}',
'items': [
for (var line_item_count = 0; line_item_count < Shopify.checkout.line_items.length; line_item_count++){
{ 'id':
'{{ item.variant_id }}',
'quantity': Shopify.checkout.line_items[line_item_count].quantity,
'price': Shopify.checkout.line_items[line_item_count].line_price
},
Shopify.checkout.line_items[line_item_count] += 1;
]
});
This is the output I'm looking to achieve:
gtag('event', 'purchase', {
'transaction_id': '123',
'items': [
{ 'id':
'53465346346',
'quantity': 2,
'price': 4
},
{ 'id':
'245643745764',
'quantity': 1,
'price': 1
}
]
});
How do I fill out an array literal with a correct JavaScript loop?
You can't use a loop in an array literal but you can use array methods to achieve the some result:
gtag('event', 'purchase', {
'transaction_id': '{{ order.order_number }}',
'items': Array(Shopify.checkout.line_items.length).fill(0).map((_, line_item_count) => {
const result = {
'id': '{{ item.variant_id }}',
'quantity': Shopify.checkout.line_items[line_item_count].quantity,
'price': Shopify.checkout.line_items[line_item_count].line_price
};
Shopify.checkout.line_items[line_item_count] += 1;
return result;
})
});
Array(Shopify.checkout.line_items.length)
creates an array with length
Shopify.checkout.line_items.length
. fill(0)
sets each element to 0
. This step is necessary because map
skips all unset elements. map(...)
contains the logic from the for loop and returns a new array.
I don't know Shopify but if Shopify.checkout.line_items
is an array or array-like you can use that array instead of creating a new array and improve the code:
gtag('event', 'purchase', {
'transaction_id': '{{ order.order_number }}',
'items': Shopify.checkout.line_items.map((el, idx, arr) => {
arr[idx]++;
return {
'id': '{{ item.variant_id }}',
'quantity': el.quantity,
'price': el.line_price
};
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.