Converting an array into an object while retaining the original input names using JavaScript

After spending all night trying various solutions, I still can't find the right answer for my Javascript needs as a beginner.

The solution I attempted to convert my form data into an object is:

$('input.submit').click(function(e){
 e.preventDefault();
 var formData = $('form.anything').serializeArray();
 console.log(formData);
});

The array output looks like the image link below:

View output of using serializeArray()

I tried using jQuery to convert it into an array of objects, but the methods I found didn't give me the desired format.

$.fn.serializeObject = function() {
var storedData = {};
var formData = this.serializeArray();
$.each(formData, function() {
  if (storedData[this.name]) {
      if (!storedData[this.name].push) {
          storedData[this.name] = [storedData[this.name]];
      }
      storedData[this.name].push(this.value || '');
  } else {
      storedData[this.name] = this.value || '';
  }
});

The output I received was this:

View output using the serializeObject()

Although the output from these attempts is closer to the object format I am looking for, there are still challenges. Hope this information helps!

Expected Output:

[
  cashin: [
    0: {
      name: [...],
      amount: [...],
      type: [...]
    },
    1: {
      name: [...],
      amount: [...],
      type: [...]
    }
  ],
  cashout: [
    0: {
      name: [...],
      amount: [...],
      type: [...]
    },
    1: {
      name: [...],
      amount: [...],
      type: [...]
    }
  ]
]

Update Information:

Here is the HTML code for the form:

<form id="cashin_form" class="anything" action="/cashins" accept-charset="UTF-8" method="post"><input type="hidden" name="authenticity_token" value="xxxx">
<!-- Form fields here -->
</form>

The input block will dynamically increase when the user clicks on the "Add Item" button. The challenge now is creating an object for each input due to the use of cashin[...] and cashout[...] in the form.

Answer №1

If you're looking for some code assistance, this snippet could be useful.

$('#cashin_form').on('submit', function(event) {

  event.preventDefault();
  
  let formdata = $('#cashin_form').serializeArray();
  
  let stored_data = {
    cashin: [],
    cashout: []
  };
  
  let temp_cashin_object = {};
  let temp_cashout_object = {};
  
  $.each(formdata, (key, obj) => {
  
    if(obj.name !== 'authenticity_token') {
    
      switch(obj.name) {
          case 'cashin[name]':
            temp_cashin_object['name'] = obj.value;
            break;
          case 'cashin[amount]':
            temp_cashin_object['amount'] = obj.value;
            break;
          case 'cashin[type]':
            temp_cashin_object['type'] = obj.value;
            stored_data.cashin.push(temp_cashin_object);
            temp_cashout_object = {};
            break;
          case 'cashout[name]':
            temp_cashout_object['name'] = obj.value;
            break;
          case 'cashout[amount]':
            temp_cashout_object['amount'] = obj.value;
            break;
          case 'cashout[type]':
            temp_cashout_object['type'] = obj.value;
            stored_data.cashout.push(temp_cashout_object);
            temp_cashout_object = {};
            break;
          default:
            break;
      }
      
    
    }
  
  });
  
 **Console.log**(stored_data);
  

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="cashin_form" class="anything" action="/cashins" accept-charset="UTF-8" method="post"><input type="hidden" name="authenticity_token" value="xxxx">


  <div id="cashin_form_item">

  <div id="cashin_form-data" class="field remove-item cashin-form-data">
      <label for="cashin_name">Name</label>
      <input type="text" value="" name="cashin[name]" id="cashin_name">
      <label for="cashin_amount">Amount</label>
      <input type="number" name="cashin[amount]" id="cashin_amount">
      <label for="cashin_type">Type</label>
      <select name="cashin[type]" id="cashin_type"><option value="1">Recurring</option>
<option value="2">This Time Only</option></select>

    <a href="#" class="remove-field btn-remove-customer">Remove Fields</a></div><div id="cashin_form-data" class="field remove-item cashin-form-data">
      <label for="cashin_name">Name</label>
      <input type="text" value="" name="cashin[name]" id="cashin_name">
      <label for="cashin_amount">Amount</label>
      <input type="number" name="cashin[amount]" id="cashin_amount">
      <label for="cashin_type">Type</label>
      <select name="cashin[type]" id="cashin_type"><option value="1">Recurring</option>
<option value="2">This Time Only</option></select>

    <a href="#" class="remove-field btn-remove-customer">Remove Fields</a></div><div id="cashin_form-data" class="field remove-item cashin-form_last">
    <!-- start input -->
      <label for="cashin_name">Name</label>
      <input type="text" value="" name="cashin[name]" id="cashin_name">
      <label for="cashin_amount">Amount</label>
      <input type="number" name="cashin[amount]" id="cashin_amount">
      <label for="cashin_type">Type</label>
      <select name="cashin[type]" id="cashin_type"><option value="1">Recurring</option>
<option value="2">This Time Only</option></select>

    <a href="#" class="remove-field btn-remove-customer">Remove Fields</a><a href="#" id="add_item">Add Item</a></div></div>
  <!-- end input -->
  <br>
     <label for="cashin_name">Name</label>
     <input type="text" value="" name="cashout[name]" id="cashout_name">
     <label for="cashout_amount">Amount</label>
     <input type="number" name="cashout[amount]" id="cashout_amount">
     <label for="cashout_type">Type</label>
     <select name="cashout[type]" id="cashout_type">
       <option value="1">Recurring</option>
       <option value="2">This Time Only</option>
     </select>
  <div class="actions">
    <input type="submit" name="commit" value="Submit Form" class="submit" data-disable-with="Submit Form">
  </div>
</form>

Your Result:

https://i.sstatic.net/LgJRw.png

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

What is the most effective method to verify if all elements in an array fall within a specified range

What is the most effective method to verify if all array values fall within a specific range? For instance: $range = range(10, 40); $array1 = array(10, 20, 40); // OK $array2 = array(11, 22, 42, 30); // FALSE $array3 = array(50); // OK $array4 = arra ...

changing the contents of an array within the current state

My current task involves updating a list of names in the state before sending it as props to another component. // code snippet omitted for brevity this.state = { // other states here playerName: { player1Name: 'Default Player 1 Name ...

Can someone provide guidance on utilizing the index correctly within this v-for to prevent any potential errors?

I am encountering an issue with using index in a v-for loop to implement a function that deletes items from an array. The linter is flagging "index is defined but never used" as an error. I am following the instructions provided in a tutorial, but I am un ...

problem encountered while processing ternary operator in Laravel

Encountering an issue here. The function below works perfectly in plain PHP and returns the correct result: $focos_3[ (array_search("$c", $cidades_3) ? array_search("$c", $cidades_3) : ('') ) ] NOTE: sometimes $c is not set. However, when atte ...

Error message stating that the function "data.map" is not recognized, resulting in a

const ShoppingList = ({ itemList }) => { let { loading, items } = itemList; console.log(items); return ( <div> {loading ? ( <p>Loading...</p> ) : ( <table> <thead> ...

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

PHP Ajax login form to instantly authenticate without redirecting to a new page

After attempting to implement Ajax in my login form by following two different tutorials, I am still facing the issue of error messages redirecting to another page instead of displaying on the same page. I have tried to troubleshoot and compare my code wit ...

Utilize jQuery to Interpret JSON data with a Customized Format

What is the best way to handle this JSON data using jQuery? {"3":[ {"project_id":27,"name":"Name1"}, {"project_id":28,"name":"Name2"}, {"project_id":29,"name":"Name3"}, {"project_id":32,"name":"Name4"} ]} ...

CSS table property remains unchanged following an ajax request

At first, my table is set to display none, making it invisible in the application. I am using an ajax call so that when a user selects an option, a table is generated and the display property changes from none to block, making it visible. However, the tabl ...

The command "npm run build:css " is not functioning properly, but when I execute the script independently, it works fine

Recently, while working on a program using npm script on my Mac system, I encountered some issues. Despite having installed node-sass globally, running "npm run build:css" did not work as expected. The content of my package.json file can be viewed here. Th ...

Utilizing Ajax in PHP to Upload Files

I'm encountering an issue while attempting to upload a file and send it via AJAX. The error message I am receiving is as follows: Notice: Undefined index: xlsFile in Here is the code snippet: HTML FORM : (this form is within a Modal Popup) <f ...

The rules function is expected to return a string or boolean value, but it received an 'object' instead

During my Vuetify validation process, I encountered an interesting situation: when I used data: () => ({, no errors were generated. However, upon changing it to data () {return {, an error surfaced stating: "Rules should return a string or boolean, rece ...

Select a date from the JQuery calendar, verify it against the database, and display any events scheduled for that date

I am working with a jQuery calendar that stores the selected date in a variable named "X". My goal is to retrieve events stored on that specific date from the Database and display them. Can anyone provide some guidance? <div id="calendar"></div&g ...

Ways to update a nested object by utilizing the setState method

I have a situation where I need to modify the key/value pairs of an object in my state. Specifically, I need to add a key/value pair to the object with an ID of 13. Please refer to the attached photo for reference. Although I know how to use setState, I ...

How to insert an image into a placeholder in an .hbs Ember template file

I'm looking to enhance a .hbs template file in ember by incorporating an image. I am not a developer, but I'm attempting to customize the basic todo list app. <section class='todoapp'> <header id='header'> & ...

Executing a function by clicking on an element with the `ng-click` directive within a Bootstrap modal

I'm working on an app that allows users to submit posts for review. When a user clicks the add post button, I have a Bootstrap modal pop up to confirm their choice. Within this modal, there is a "confirm" button that should trigger a function. Strang ...

Tips for converting each item within an array into its own separate element

https://i.sstatic.net/Dxj1W.pngI currently have an array of objects that I am utilizing to generate a table in Angular. The table is functioning properly and successfully displays the data. However, I now have a requirement to enable editing for each indiv ...

Guide to converting an arraylist of custom objects into JSON using JavaScript

I have a List returned to the jag. It is of type (java.util.List) and I need to print it as a json. var storeForum = Packages.org.wso2.carbon.forum.registry.RegistryForumManager; var forum = new storeForum(); var start = request.getParameter(&a ...

HTML/JavaScript - Ways to show text entered into an input field as HTML code

One dilemma I'm facing involves a textarea element on my website where users input HTML code. My goal is to showcase this entered HTML code in a different section of the webpage. How should I approach this challenge? The desired outcome is similar to ...

Highlight text when the user is scrolling the page - using JQUERY

Can anyone suggest a way to dynamically underline text as the user scrolls down a webpage? The underline should only be visible while the user is scrolling. I've experimented with animate.css and other plugins, but haven't been able to achieve th ...