Transforming a Formdata object into a JavaScript array

Greetings everyone! Is there a way in JavaScript to convert this data structure:

{ 
 Control[0].Eseguito: "true"
 Control[0].Id:"2"
 Control[0].Nota:""
 Control[1].Eseguito: "true"
 Control[1].Id:"2"
 Control[1].Nota:""
}

into a JavaScript Array like this:

Control: Array(2)
0: {Id: '1', Eseguito: "true", Nota: ''}
1: {Id: '1', Eseguito: "true", Nota: ''}

UPDATE

let myForm = document.getElementById('ControlForm');
var Controls = Object.fromEntries(new FormData(myForm).entries());

In my ExecControl.cshtml file, I have a situation similar to this, just a snippet of the code:

@{
    int Index = 0;
}

@for (int i = 0; i < Model.ListControls.Length; i++)
{
    for (int j = 0; j < Model.ListControls[i].Controls.Length; j++)
    {
        ...
        <input type="text" style="width:100%;" name="Control[@Index].Nota"/>
        input type="text" style="width:100%;" name="Control[@Index].Id" value="@ListControls[i].Controls.Id"/>
        ...
    }
}

Answer №1

You have the ability to transform data of only [index] type into an array using this particular technique.

var formData = new FormData();
formData.append("Control[0].Id",1);formData.append("Control[0].Nota","Notaval");formData.append("Control[1].Id",2);formData.append("Control[1].Nota","Nott");

function arrayConversion(data){
  var result = [];
  for (const [key,value] of data.entries()) {
      if(!key.includes("[") || !key.includes("]")) {return;}
      var indexVal =  key.indexOf("[") + 1;
      var indexVal2 =  key.indexOf("]");
      var index = parseInt(key.substring(indexVal,indexVal2))
      if(index == NaN){ return;}
      var field = key.split(".")[1]
      result[index] = {...result[index],[field]:value}
    }
   return result;
}
 console.log(arrayConversion(formData));

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

The affix feature in Bootstrap's navbar fails to recognize the height of images

My navbar element affixes prematurely when placed below my header element, making it seem as if the image in the header does not exist. The navbar is meant to affix only when it reaches the top, but currently, it is affixing earlier. The code I used sets ...

Setting up JavaScript imports in Next.js may seem tricky at first, but with

Whenever I run the command npx create-next-app, a prompt appears asking me to specify an import alias. This question includes options such as ( * / ** ) that I find confusing. My preference is to use standard ES6 import statements, like this: import Nav f ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

Ways to expand the dimensions of a Popup while including text

I am using a bootstrap modal popup that contains a Treeview control in the body. The issue arises when the node's text width exceeds the popup's width, causing the text to overflow outside of the popup. Is there a way to dynamically adjust the ...

PHP Loop News/Image Slider with Clickable Interval Reset and Improved Unique ID Formatting

Currently, I am in the process of setting up a news/image slider on my website using JavaScript. I have the slide data coming through a PHP loop with unique IDs, which is functioning smoothly. However, I am struggling to figure out how to reset the timer/i ...

What is the best way to retrieve information from a JavaScript file?

Learning.vue <template> <div> <button @click="test()">test</button> </div> </template> <script> import records from './records.js' export default { data () { return { ...

Creating interactive web applications with Python Flask by utilizing buttons to execute functions

When the button is clicked in my Flask template, I want it to trigger a Python function that I defined in app.py. The function should be accessible within the template by including this code where the function is defined: Here is an example function in ap ...

Dragging a Google Maps marker causes a border to appear around a nearby marker

Recently, I added a main draggable marker to the map. However, an unusual issue arises when dragging this marker - a blue outline appears around one of the existing markers on the map. This behavior is puzzling as it seems to be triggered by a click event ...

Using the spread syntax to eliminate a property from an object within a ReactJs element

I'm trying to figure out if it's possible to remove a specific object property using spread syntax when rendering a React component. I want to achieve this without adding too much extra code. Currently, I am utilizing {reset,...inputName} In my ...

Creating a Wordpress Metabox that utilizes radio inputs generated with Javascript instead of the traditional checked() function in Javascript as an alternative

Despite my efforts to find a solution on various forums, I am still stuck with this issue without making any progress. The code snippet below contains two Radio inputs. These inputs are generated on the post edit page of Wordpress CMS and their values com ...

Having trouble transferring data between Vue.JS components

Wondering how to pass data from the parent component (Home route) to the child component (playlist route) using props? Encountering a "TypeError: Cannot read property 'length' of undefined" error in the child component? These two components are c ...

The error message "Cannot access 'id' property of undefined" is being displayed

I have a file named auth.js along with a middleware called fetchuser. The code provided below is causing an error that I cannot figure out. The error occurs during the process of sending a token to the user and verifying whether the user is logged in or n ...

Transferring properties from React Router to child components on the server side

For my Isomorphic app using React, react-router v3, and material-ui, it's crucial to pass the client's user agent to the theme for server-side rendering. This is necessary for MUI to properly prefix inline styles. Initially, the root component o ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

Executing an HTTP POST request without properly encoding a specific parameter

I am attempting to communicate with an unauthorized third-party API using Node and the request module. Below is the code that generates the request: request.post( { url: url, headers: MY_HEADERS_HERE, followAllR ...

HTML/Javascript/CSS Templates: Keeping Tabs on Progress

I'm looking for templates that use notepad as an editor for html/javascript/css. I want to find a template that displays text or pictures upon clicking, like the example below: https://i.sstatic.net/qsFYs.png Sorry if this is a silly question, it&ap ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

Storing data values from a specific object key into an array in Vue: Step-by-step guide

Just dipping my toes into the world of Vue framework here. I managed to create a selectable table that stores data in an object. I want this function to run in the background, so I figured it should be in the computed section. The object structure is as fo ...

Unable to retrieve real-time data from Firestore using getStaticPaths in Next.js

While fetching data from Firebase Firestore using getStaticProps is successful, I encounter a 404 page when attempting to implement the logic for retrieving details of individual items with getStaticPaths. The current state of my [id].js code appears as fo ...

"Learn how to use jQuery to transform text into italics for added

Within my ajax function, I am appending the following text: $('#description').append("<i>Comment written by</i>" + user_description + " " + now.getHours() + ":" + minutes + ">>" + description2+'\n'); I am intere ...