0

So, I'm building an API in Ruby on Rails and I'm trying to force an array to be sent through ajax.

It seems quite an easy task if it wasn't for the fact that the array is being received as an associative array other than regular array!

Basically an array with objects like:

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

becomes:

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

instead of

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

This is the JS I'm using 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);

         })
}

How can I transform my payload to go as a regular array instead of associative?

4
  • why not use var shipments = {"$1": obj2,"$2": obj3}; ??? Commented Apr 5, 2020 at 2:39
  • You can process shipments dynamically, is only you knew how obj1 and obj2 values are retrieved. is there possibly more objects to be submitted? Commented Apr 5, 2020 at 2:41
  • it seems that someone asked about your same scenario and got an answer stackoverflow.com/a/38175543/615274 Commented Apr 5, 2020 at 3:58
  • Are you sending the request as JSON? If its treated as form data then Rack encodes an array of hashes as foo[0][foo]=bar thats because if you encode it as foo[][foo]=bar Rack has no way of knowing which hash the key belongs to. Also "associative arrays" are not a thing in Ruby - that's just a hash, and if you want to "cast" it into an array you just call hash.values and this is automatically done with strong parameters. Commented Apr 5, 2020 at 7:31

1 Answer 1

0

You can do the following:

Note that this solution can process any number of shipments.

var shipments = [
  {
      "shipping_id":"1",
      "option":"1"
  },
  {
      "shipping_id":"2",
      "option":"2"
  }
]

var payload = {}

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

console.log(payload);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.