What is the best way to transform a collection of items into FormData?

In my current project, I have a JavaScript array structured as follows:

var items = [{
   ID: "1"
   count:'1',
   File: (binary file)
   },
   {
   ID: "2"
   count:'2',
   File: (binary file)
   }
]

My goal is to retrieve the file input on the backend by utilizing multipart + formData. However, I am struggling to convert the list into the required format. Could someone please guide me on how to achieve this task successfully? Thank you in advance.

Answer №1

Yes, you are capable of achieving this task.

var elements = [
    {
        ID: "1",
        count: "1",
        File: "file",
    },
    {
        ID: "2",
        count: "2",
        File: "file",
    },
];

var formContent = new FormData();

formContent.append("firstId", elements[0].ID);
formContent.append("secondId", elements[1].ID);

//inside a loop
elements.forEach((element, index)=>{
  formContent.append("id_" + index, element.ID)
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adapting language in real-time: DateTimePicker jQuery Plugin

I am looking to dynamically adjust the language settings of the DateTimePicker jQuery Plug-in (http://xdsoft.net/jqplugins/datetimepicker/) but I keep encountering an "undefined" error for the lang1 variable within the final plug-in function call: <!DO ...

Reveal or Conceal Information Depending on Cookie Status

Below is the Jquery code I am using: $("#tool").click(function() { $(".chelp").slideToggle(); $("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#tool img").toggle(); }); }); When the #tool img is clicked, bot ...

The React server-side rendering isn't reflecting changes made on the client-side route

Upon the first refresh, both the server and client side are updated; however, subsequent updates only affect the client side when switching pages with react router. For instance, refreshing the page or entering a new URL causes changes on the server and t ...

Issues with React Router functionality on a live production site are causing complications

I recently created an Amazon-clone UI using create-react-app, but it only displays dummy data. The issue arises after deploying it to Vercel - the routing does not function as expected. When clicking on links, a blank page appears with correct URL paramete ...

Retrieving data from server file and showcasing results on client interface

After reading a file from the server side, I have stored its contents in a list and sent it to a template. Now, my main concern is how to access this list in order to display the file's contents line by line. To achieve this, I am utilizing AJAX and j ...

Cease the AJAX Requests

In order to successfully load my page, I have implemented a series of AJAX POST requests in a specific sequence using the .done() function: $(document).ready(function(){ // Load Recipients & documents $("#page").hide(); $("#loading").show( ...

Experiencing a "non-serializable value found in the state" error specifically while utilizing redux toolkit, but this issue does not occur with traditional redux implementations

While transitioning my app to utilize Redux Toolkit, I encountered an error after switching over from createStore to configureStore: A non-serializable value was found in the state at path: `varietals.red.0`. Value:, Varietal { "color": "red", "id": " ...

Leveraging the NextAuth hooks, employ the useSession() function within the getServerSideProps

I'm currently working on retrieving data from my server based on the user who is logged in. I am utilizing Next-Auth and usually, I can easily obtain the session by calling: const { data: session } = useSession(); In a functional component, this work ...

"Utilizing JSON parsing in Node.js and rendering the data in a Jade template

I need assistance with parsing JSON and presenting the response in a tabular format using Jade. Can you help me display the key-value pairs in two separate columns? Node.js exports.postMQinput = function(req, res) { req.assert('name', 'Q ...

Selecting the child checkbox within the parent div using ng-click

Is there a way to trigger the click event of a parent div on its child checkbox in AngularJS? The Checkbox will have the attribute hidden, necessitating the parent div to act as the clickable element. Sample HTML: <body ng-app="checkboxApp"> ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

What is the best approach for creating personalized AJAX requests with the least amount of code?

Currently working on a nested comments system and I am exploring the most lightweight method to perform simple AJAX calls. While JQuery offers some AJAX capabilities, I wonder if there is a more minimal option available such as using XMLHttpRequest direc ...

Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted : if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "wind ...

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

Steps for interacting with a button of the <input> tag in Selenium using Python

As I attempt to complete a form submission, I encounter an issue where clicking the submit button does not produce any action. It seems that the problem lies with the button being tagged as <input>: <input type="submit" name="submit ...

What is the best way to add a separator in a b-dropdown menu once the options have been loaded using Vue?

Here is the code snippet for my dropdown element: <b-dropdown id="SchemaDropdown" name="SchemaDropdown" variant="form-control" class="" style="width: 100%" ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

Angular 1.4.8 Issue: [$injector:modulerr]

I can't seem to identify the main cause of this error. I consistently see a green underline below the word angular in my javascript file. I'm not sure why. (Using Visual Studio Code) HTML <html ng-app="myapp"> <head> ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

Successive promises of catches

Here is a situation that I am dealing with: controller.ts methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); }); } service.ts someMethod(): ng: ...