Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda