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

184
Visualizações
How to send multiple data to server using for loop
const submit = e => {
    e.preventDefault();
    fetch('', {
      method: 'POST',
      body: JSON.stringify({
        product_option_id: 1,
        quantity: 2,
      }),
    })
      .then(response => response.json())
      .then(result => {
        if (result.success) {
          goToCart();
        } else {
          alert('error');
        }
      });
  };

I have a question regaring sending data to backend using fetch. I have product_option_id in array format as result = [4, 3] for example. And I have quantity in array format as count = [1, 2] for example accordingly. So here I have product_option_id: 4 and its quantity is 1 and I also have product_option_id: 3 and its quantity is 2. If I have to send these data separately one after another one as above instead of sending array, can I write an if statement like this in body?

fetch('', {
      method: 'POST',
      body: JSON.stringify({
        for (let i =0; i < result.length; i++) {
        product_option_id: result[i],
        quantity: count[i],
        }
      }),
    })

Thank you in advance.

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

0

Firstly, an overview of your objective. You have the following data structures:

const result = [6, 7, 8];
const count = [1, 2, 3];

... and you want to send them to the server as an array of objects like:

[
    { "product_option_id": 6, "quantity": 1 },
    { "product_option_id": 7, "quantity": 2 },
    { "product_option_id": 8, "quantity": 3 }
]

To do this, you are on the right lines, but you can't use a for loop inside another line. Try replacing your 'for' with a call to Array.map() as follows:

function transform(result, count) {
    return result.map((r, index) => ({
        product_option_id: r,
        quantity: count[index] || 0
    });
}

const submit = e => {
    e.preventDefault();
    fetch('', {
      method: 'POST',
      body: JSON.stringify(transform(result, count)),
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            goToCart();
        } else {
            alert('error');
        }
    });
};

I refactored your code into smaller functions to make it easier to read for the benefit of anyone reading this, but you could call result.map inline inside your original function.

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