简体   繁体   中英

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM