Transformation of an Ajax array into an associative array

Currently, I am working on creating an API using Ruby on Rails and facing a challenge with sending an array through ajax.

The task seems straightforward, but the issue arises when the array is received as an associative array instead of a regular one!

Essentially, the array with objects like:

[
        {
            "shipping_id":"1",
            "option":"1"
        },
        {
            "shipping_id":"2",
            "option":"2"
        }
]

is transformed into:

{"0"=>{"shipment_id"=>"1", "option"=>"1"}, "1"=>{"shipment_id"=>"2", "option"=>"2"}}

rather than

[{"shipping_id"=>"1", "option"=>"1"}, {"shipping_id"=>"2", "option"=>"2"}]

Below is the JavaScript code I am utilizing to test the API:

function select_shipping(){

        obj1 = {
            "shipment_id": "1",
            "option": "1"
        };

        obj2 = {
            "shipment_id": "2",
            "option": "2"
        };
        var shipments = [obj1, obj2];
        var payload = {
            user_options: shipments
        }

        $.post('/shipping/calculate/select',   // url
        payload, // data to be submit
        function(data, status, jqXHR) {// success callback
            console.log(data);

         })
}

I am looking for a solution to transform my payload into a regular array format instead of an associative array. Any suggestions?

Answer №1

Here are the steps you can take:

Keep in mind that this approach is capable of handling numerous shipments simultaneously.

let shipments = [
  {
      "shipping_id":"A",
      "option":"X"
  },
  {
      "shipping_id":"B",
      "option":"Y"
  }
]

let payload = {}

shipments.map(
  function(shipment, index){
    payload["$".concat(index)] = shipment;
  }
);

console.log(payload);

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

Guide on accessing the text content within a div element in HTML by triggering a button click

To extract specific text from multiple div tags, I need to trigger an event when clicking a button. <div class="col-lg-3 col-md-6 mb-4"> <div class="pricing-table pricing-secondary"> <div class="price-hea ...

Guide on showcasing various PHP tables based on the selection from a PHP combobox

I am facing a challenge where I need to retrieve multiple queries and display each query in a PHP table when a specific item is selected from a combobox. For instance, upon clicking on the first item listed below, the corresponding table with its respect ...

Trouble with JavaScript preventing the opening of a new webpage

I need help with a JavaScript function to navigate to a different page once the submit button is clicked. I have tried using the location.href method in my code, but it's not working as expected. Even though I am getting the alert messages, the page i ...

The Django CSRF verification has failed, causing the request to be aborted. There seems to be a missing or incorrect CSRF token even though

My HTML page, created with WYSIWYG, features a large form containing numerous values that I need to send back to my view in order to incorporate them into the template. Currently, everything is functioning correctly as I am able to successfully send my va ...

Adjust variable values when the window is resized

I've been working on getting some variable values to update when the window is resized. After researching, I learned that it's recommended to declare the variables outside of the .resize function scope and then try to change their values within ...

Mapping an array using getServerSideProps in NextJS - the ultimate guide!

I'm facing an issue while trying to utilize data fetched from the Twitch API in order to generate a list of streamers. However, when attempting to map the props obtained from getServerSideProps, I end up with a blank page. Interestingly, upon using co ...

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Error: Unable to simplify version range

Attempting to follow the Express beginner's guide. I created an app and executed npm install as per the provided instructions. > npx express-generator --view=pug myapp > npm install npm ERR! semver.simplifyRange is not a function npm ERR! A com ...

Position the Bootstrap Modal at the start of the designated DIV

When using a Bootstrap Modal to display larger versions of thumbnails in a photo gallery, there can be some challenges. The default behavior of Bootstrap is to position the modal at the top of the viewport, which may work fine in most cases. However, if th ...

Strategies for aligning a div element in the middle of the screen

Positioned in the center of the current viewport, above all other elements. Compatible across different browsers without relying on third-party plugins, etc. Can be achieved using CSS or JavaScript UPDATE: I attempted to use Javascript's Sys.UI.Dom ...

When using JSON stringify, double quotes are automatically added around any float type data

When passing a float data from my controller to a JavaScript function using JSON, I encountered an issue with quotes appearing around the figure in the output. Here is the JS function: function fetchbal(){ $.ajax({ url: "/count/ew", dataType: "jso ...

Refreshing the webpage without reloading using Ajax ResponseText

While the form successfully sends data to the MySQL database, it is unable to display the responseText within the specified <div id="ajaxGetUserServletResponse"></div>. How can I retrieve the response? <form id="form-id" class="ajaxform" ac ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

The confirmation dialogue is malfunctioning

Need some assistance with my code. I have a table where data can be deleted, but there's an issue with the dialog box that pops up when trying to delete an item. Even if I press cancel, it still deletes the item. Here is the relevant code snippet: ec ...

Guide to integrating various HTML files into a single HTML file with the help of Vue.js

Although I am familiar with using require_once() in PHP, unfortunately, I am unable to use PHP in my current project. I attempted to use w3-include from W3Schools as an alternative, but encountered issues with loading my scripts. Even utilizing JavaScript ...

Discrepancy in functionality between .show() and .append() methods within JQuery

I have a container with an ID of "poidiv" that is hidden (display: none) initially. My goal is to dynamically load this container multiple times using a loop, where the maximum value for the loop is not predetermined. I attempted to achieve this using jQue ...

The features of findOneAndRemove and findOneAndUpdate are not functioning optimally as expected

Attempting to create a toggle similar to Facebook's "like" feature. The code functions correctly when there are no existing "likes." It also deletes properly when there is only one "like" present. However, issues arise when multiple likes accumulat ...

Retrieve information from an HTML form, make updates to the database, and exhibit the data in a table on the current page with the help

I'm in need of some assistance. I have a small application that utilizes a Java Servlet and an HTML form. The user enters data into the HTML form, and upon clicking the submit button, the Java servlet retrieves this data in its post method and stores ...