Hello. Help build a json request structure.

I have already bothered to do all sorts of variations, I sit on it for the first time, so I ask for help.

There is a form, I make a sample from a form using serializeArray() . It's all okay, the structure is built right. Next, in addition to the data from the form, I need to send other data that will look like:

 var myObj = { "flavors": [ {"id":"id", "value": "value"}, {"id":"id", "value": "value"} ], } 

How can I properly "cross" the data from the form and other data ( flavor[] )? How is it usually done? Maybe I'm just fixated on something incomprehensible, and everything is done much easier !? enter image description here

It does not quite work out as it should, I don’t know how best to combine the data so that it would be easier on the server to work with all the data .. I tried it this way ...

 var myObj = { "flavors": [ {"id":"id", "value": "value"}, {"id":"id", "value": "value"} ], "form": [ ] }; var inputs_data = $(this).serializeArray(); myObj.form.push(inputs_data); 

The output is as follows:

enter image description here

  • it all depends on the form in which this server is waiting for you, but it is better not to mix milk and cucumbers, but to send 2 arrays of objects lying nearby. For example: var myObj = { "flavors": [], "form": [] }; -
  • Understood, and how you can var inputs_data = $ (this) .serializeArray (); to push in myObj? - axblue
  • I tried it, see the edited question - axblue
  • myObj.form = inputs_data - myObj.form = inputs_data
  • Got it. Then please explain why when I send only inpust_data, I get an answer in this form prntscr.com/dt2x4a And when I combine it, then prntscr.com/dt2xxm . On the server it will not be very convenient to work with such a view .. - axblue

1 answer 1

I solved my question like this:

  var myObj = { "flavors": [ {"id":"id", "value": "value"}, {"id":"id", "value": "value"} ], "form": [ ] }; var inputs = {}; $.each($(this).serializeArray(), function(i, field) { inputs[field.name] = field.value; }); myObj.form = inputs; 

I get this kind of data:

  array:2 [▼ "flavors" => array:2 [▼ 0 => array:2 [▼ "id" => "id" "value" => "value" ] 1 => array:2 [▶] ] "form" => array:8 [▼ "name" => "" "descr" => "" "image" => "" "_token" => "O2tQBPsByYbfjvcMxghp4uHxodRNHFdPbvXx6kw9" "volume" => "3" "nic" => "3" "pg_value" => "50" "premium" => "on" ] ]