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

Determining the precise spacing needed for a personalized cursor

Currently, I'm facing an obstacle in my attempt to design a custom cursor/crosshair inside a canvas. The problem lies in the Length, Width, and Gap dimensions assigned to the four rectangles that make up the cursor, as it is resulting in an incorrect ...

Refresh Ajax/Javascripts following the loading of new data with .html() function

My website has a page that utilizes an ajax function to load data into the page. The ajax function is as follows: $(document).ready(function(){ function loadData(page){ $.ajax ...

"Enhance your website's tracking capabilities by integrating jQuery with

Last week, everything was working perfectly fine and I hadn't made any changes to the code or settings. The google analytics javascript file is loaded using the .htaccess file, ensuring it is consistently used for all pages without any issues. However ...

Determine the number of distinct elements in fields using MongoDB aggregation

After executing my query, I received documents in the following format: { _id: '48nmqsyxmswpkkded2ac_331fabf34fcd3935', actions: { sales: { pixel: [Object] } }, date: Sun Jul 27 2014 00:00:00 GMT-0400 (EDT), client: '48nmqsyxmswpkkded ...

Unexpected behavior seen with the mysql_num_rows() function

I am encountering an issue where the if loop does not run even though I have 5 records in my table, resulting in an error message: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Crud\ ...

What methods can I use to retrieve traversed objects using riak-js?

Utilizing Node with riak-js to interact with a Riak database. I have established two buckets named invites and events. The invites bucket contains a link to events. Is there a way to fetch both the invite object and the corresponding event object in one qu ...

Allowing Cross-Origin Resource Sharing on an Express Server hosted using Firebase Cloud Functions

Hey there, I have a simple Express setup on Firebase, shown below: import { onRequest } from 'firebase-functions/v2/https'; import express from 'express'; import bodyParser from 'body-parser'; import router from './router ...

If you refer to a function, are you personally calling the function or asking the reference to call it?

From what I understand, and please correct me if I'm mistaken, when a variable is assigned to a function in the form of a function expression, it doesn't hold the function in the same way that it holds a primitive value. The variable simply refer ...

The issue arises when Node.js fails to identify the input fields that were dynamically inserted into the form

I came across a question similar to mine, but I found it challenging to apply the solution to node js. In my project, users can add items to a cart by clicking on them, which are then dynamically added to a form using jquery. However, upon submission, only ...

Verify if the contract address corresponds to a token and retrieve the token details, such as its symbol

Can I use web3 to retrieve token information such as symbol and total supply similar to the etherscan API pro endpoint tokeninformation by providing the contract address? I'm interested in determining whether the addresses I collect are tokens or reg ...

Display a collection of Mongoose objects in a React component

In my development stack, I rely on node js + React. The data I work with comes from mongoose and typically follows this format: { "_id": "61b711721ad6657fd07ed8ae", "url": "/esports/match/natus-vincere-vs-team-liquid- ...

A guide on utilizing bootstrap tooltip feature to display information when hovering over an image

I have a jQuery function that dynamically creates an image and li element on the page. My goal is to implement a bootstrap tooltip so that when the mouse hovers over the image, additional details about it will be displayed in a separate tooltip similar t ...

Exploring the Interaction of Users with HTML Table Cell <td>

I am currently analyzing the code for a web page. Within this code, users have the ability to double-click on a cell in a table (<td> as shown below) and input a value. Is there a specific attribute or element within this HTML that indicates user in ...

Modify the URL query to read as "favicon.ico"

Whenever I make a GET request to my node.js/express web server with a URL following the route, instead of storing that URL, the server ends up saving favicon.ico: var express = require("express"); var app = express(); app.get("/:query", function (req, re ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

Trigger an asynchronous method using AJAX when the page loads

Currently, I am utilizing ASP.NET 2.0 along with AJAX Extensions (possibly version 1.0) and I am curious if there is a way to invoke a method asynchronously and display the results on the page once it has finished loading. More specifically, I have a grid ...

How to override an event in JavaScript when a specific value is entered

I am looking to implement a system with complex conditions. The goal is to have an alert appear when a value is inputted and the button is clicked. First, a confirmation message Have you input ? should be displayed, followed by clicked with input. If no va ...

Extension for Chrome

My goal is to develop a Chrome extension that, when a specific button in the extension is clicked, will highlight the current tab. However, I'm encountering some challenges. Currently, I have document.getElementById("button").addEventListen ...

Node.js post request body is still showing as undefined despite using body-parser

Hello everyone, I am currently using Node.js to implement a Dialogflow chatbot. My goal is to extract parameters from an HTTP POST request. To achieve this, I utilized Postman and made sure to set the content type to JSON in the header. Below is the code f ...

Why is Node.js unable to locate my files?

I'm currently utilizing Node.js as my server, and I'm encountering some difficulties in serving my JS and CSS files. For some reason, index.html is unable to locate them. Whenever I try to load up my browser, I encounter the following error: htt ...