How to send array of objects in formdata in react js

To send an array of objects as FormData in React JS, you can follow the steps below:

  1. Create an array of objects containing the data you want to send.
  2. Create a new instance of FormData.
  3. Loop through the array of objects and append each object to the FormData instance as JSON string using the append() method.
  4. Send the FormData through an HTTP request, such as using the fetch() function.

Here’s an example of how you can achieve this:

    {`const data = [
  { name: "John", age: 25 },
  { name: "Jane", age: 30 },
  { name: "Jake", age: 35 }
];

const formData = new FormData();

data.forEach((obj, index) => {
  formData.append(\`object$\{index}\`, JSON.stringify(obj));
});

fetch("http://example.com/api/endpoint", {
  method: "POST",
  body: formData
})
  .then(response => response.json())
  .then(result => {
    // Handle the response
  })
  .catch(error => {
    // Handle any errors
  });
`}
  

In the above example, we have an array of objects called “data”. We create a new instance of FormData and then loop through the array of objects using forEach. Inside the loop, we append each object to the FormData instance by converting the object to a JSON string using JSON.stringify(). Each object is appended with a unique name, such as “object0”, “object1”, etc.

Finally, we make a POST request to the desired endpoint with the FormData as the request body. After that, you can handle the response or any potential errors.

Leave a comment