Transform a dynamic list object in a form into JSON using javascript

I have been using a form submission script that converts form inputs to JSON and submits with ajax. It has worked well for simple forms in the past, but I am encountering an issue when trying to use it for lists.

Within the form, there is a dynamic list of inputs generated by another script. The structure of the list items is as follows:

<li><input type="checkbox" name="skill_list[]" value="10155"></li>

The function responsible for reading the form is shown below:

var formToJSON = elements => [].reduce.call(elements, (data, element) => {

  data[element.name] = element.value;
  return data;

}, {});

When the submit button event listener is triggered, the function is called like this:

var data = formToJSON(this.elements);

Prior to submission, the data undergoes stringification:

var data = JSON.stringify(data);

An error arises within the formToJSON function. Instead of creating an object with the property name skill_list and values such as {10155, 10288, 10240}, it generates an object with the name skill_list[] where the value corresponds to the initial value in the list.

I have attempted modifying the function to handle lists without success, and I am seeking guidance on how to proceed in solving this issue.

PS. Ideally, I would like to achieve this without relying on jQuery.

Answer №1

To efficiently process an array of elements, you need to handle each element individually:

const convertToArray = elements => [].reduce.call(elements, (data, element) => {
  const isArray = element.name.endsWith('[]');
  const name = element.name.replace('[]', '');

  data[name] = isArray ? (data[name] || []).concat(element.value) : element.value;
  return data;
}, {});

Answer №2

To transform form data into a JSON object, consider using the steps below

const jsonFormData = JSON.parse(JSON.stringify($('#form').serializeArray()));

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

Incorporating intricate HTML elements through a Chrome content script

Currently, I am utilizing Chrome extension's content script to generate a sophisticated display that is incorporated into web pages. Initially, I tested it by integrating it directly onto a website, but now I want to package it in an extension. The ...

Tips for personalizing the datetime format of JSON before the web API transmits the response

Is there a way to customize the DateTime format returned by my webapi, as the default one is not suitable for my needs? ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

Enhance an existing webpage by integrating ajax with jquery-ui

I'm seeking assistance with integrating an advanced search feature into an existing webpage system. It appears that there is a complication with the current jQuery UI being used on the page: <script src="js/jquery-ui-1.10.4.custom.js"> ...

Google Sheets API v4 - Add a Row Above (Not Below)

Is anyone familiar with how to use the insertDimension request to insert a row above existing data? I am having trouble finding documentation on specifying where to add the row within the spreadsheet. The code I have inserts the row at the bottom, and I&ap ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

Unexpected behavior in React-Native when filtering array objects

I am currently working on a react-native project where I am dealing with an array object that is being fetched from the backend. Here is a snippet of the Array. { "2010":[ { "id":1243, "eventName": ...

How can the value attribute be obtained from the click class?

$(document).on('click','.edit', function(){ var appid = $(this).getAttribute('value'); I am trying to figure out how to save the value of the "value" attribute for an image with the edit class. Can anyone help me with thi ...

CSS class for Angular drag-and-drop functionality during drag operation

I have implemented the Angular dragdrop functionality in my application. Currently, I am looking to modify the border color of the drop area when an item is being dragged over it. Is there a specific CSS class that I can utilize for achieving this? If no ...

Unable to activate slideToggle due to malfunctioning links

When using the slideToggle function, I encountered an issue where the links are not functioning properly. Check out my demo site at the following link: Here is my script: $(".nav li > a").click(function(e) { $(this).parent().siblings().find(&a ...

The persistent Expo in-app purchase sandbox pop-up continues to plague, hindering the completion of the test purchase

After creating my app using Expo and integrating Revenuecat for payments, I encountered an issue while testing it. Whenever I try to subscribe, the purchase popup keeps reappearing in Sandbox mode even after clicking 'Done'. Despite entering vali ...

Clearbox JS "notifications"

Currently, I have integrated Clearbox JS on my website to allow users to view larger versions of images after visiting the images page. However, I have noticed that on every single page, Clearbox JS displays a message at the top of the page indicating what ...

The jQuery change function appears to be functioning properly, but it is not producing any results

I am facing an issue with my jQuery code that rebuilds a dropdownlist based on the radio buttons selected. Although the code seems correct and the method works properly, the dropdownlist items do not update as expected. Can anyone provide some insight or i ...

Clicking on the button will allow you to sort the items in

I need assistance with sorting a table: when I click on a header, the order changes to ascending but does not toggle back to descending. Despite having a boolean value that should switch between true and false, it keeps returning the initial value. Can s ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Tips for retrieving JSON data using Backbone.js

I'm experimenting with using backbones.js fetch to retrieve json from a twitter search and I need some help figuring out what's wrong with my code below. Can someone lend me a hand? (function($){ var Item = Backbone.Model.extend(); var Li ...

Importing JSON data into a pandas data frame and defining personalized fields

Examining this sample JSON data as part of my current project. { ":@computed_region_amqz_jbr4": "587", ":@computed_region_d3gw_znnf": "18", ":@computed_region_nmsq_hqvv": "55", ":@computed_region_r6rf_p9et": "36", ":@computed_region_ra ...

Is there a way to use nightwatch.js to scan an entire page for broken images?

Hi there, I'm currently working on creating a test to ensure that all images are loaded on a webpage with just one single test. I assumed this would be a straightforward task that many people have already done before, but unfortunately, I haven' ...

Error: The configuration object provided for initializing Webpack does not adhere to the correct API schema in Next.js. This results in a ValidationError due to the invalid configuration

When I used create-next-app to set up my next.js project, everything seemed fine until I tried running npm run dev and encountered this error: ValidationError: Invalid configuration object. Webpack has been initialized using a configuration object that doe ...

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...