Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
JavaScript For Loop To Fill In Array

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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
        };
    })
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda