6
  'recipient.firstName': 'Fred',
  'recipient.lastName': 'Johnson'

Is there any elegant way to turn this into:

var recipient = {
  firstName: 'Fred',
  lastName: 'Johnson
}

Using JS on the frontend? I want to POST JSON but it doesn't seem like that is done very easily with HTML, therefore I want to intercept the POST with jQuery and format it into the JSON I want.

EDIT: I am leaving the original question above for clarity's sake, but if you read closely you will see that the issue I have is not posting the data with AJAX to a REST API. That's very simple and already implemented. What is happening is that I am dynamically building forms using a template engine that I have created, and the forms id and names are built to represent nested data such as recipient.firstName. However, when I receive this data passed as JSON to the API endpoint, I need to transform it programatically from the first format to the second format, which is what the question is actually asking if you read it closely. Sorry for any confusion, the answer I have listed below solves the question.

Anthony
  • 13,434
  • 14
  • 60
  • 80
  • 1
    You should try something and then ask a question. Iterate over the properties, look for properties with dots and create sub-objects for those properties. Doesn't seem so hard, I don't want to write the code and keep you from a learning experience – Ruan Mendes Nov 12 '15 at 23:28
  • 1
    Yes Juan, that's basically what I'm writing right now. – Anthony Nov 12 '15 at 23:30
  • stringify the object, replace recipient. with blank and parse the string. JSON.parse(JSON.stringify(original).replace(/recipient\./g,'')) – Jules Nov 13 '15 at 01:00

4 Answers4

1
var recipient = [{firstName: "Fred",lastName: "Johnson"}]
                //:: CONVERT TO JSON
                recipient = JSON.stringify(recipient);
                //:: POST THE DATA 
                $.post(LINK_url,{post_recipient : recipient },json/*:: json not important, it can be auto guessed. delete ',json' */,function(output){
                    //var data =jQuery.parseJSON(output);});

______________________________edit_______________________________________

if i get you right this time your output is plan text and you need to convert to json, if so try this.

var recip = JSON.stringify[{ output }];
var data = jQuery.parseJSON(recip);
var viewdata='';
$.each(data, function(key, recipient){viewdata +=
recipient.firstName +" "+recipient.lastName+"<br/>"
})
prompt(viewdata);
Timothy Nwanwene
  • 995
  • 11
  • 18
0

With jQuery with a form by Using serializeArray() and forEach and other object:

$(function() {
  var recipient = $("#frm").serializeArray();
  var output = {}; // Declare an object.

  recipient.forEach(function(v, i) {
    output[v.name] = v.value; // Assign the current value to the current key.
  });

  $.ajax({
    url: "http://httpbin.org/post",
    type: "POST",
    data: JSON.stringify(output), // Send the object.
    contentType: "application/json",
    success: function(response) {
      //console.log(response);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="frm" method="post">
  firstName:
  <br/>
  <input id="firstName" name="firstName" type="text" value="Fred" />
  <br />lastName:
  <br/>
  <input id="lastName" name="lastName" type="text" value="Johnson" />
  <br />age:
  <br/>
  <input id="age" name="age" type="text" value="30" />
</form>

In the request, you send: enter image description here

0

UPDATE

Now that I know your server side is NodeJs you simply need to learn how to call NodeJS server side methods:

How to send data from JQuery AJAX request to Node.js server

So your approach is just wrong, you have this unnecessarily complex string of data that you want to intercept. Do not intercept anything, send a well formatted HTTP POST from the start, with jQuery or Javascript to your server Controller or API. The signature of your API method should be:

DoSomethingWithRecipient(string firstName, string lastName);

Your recipient should have a userId as well but that is up to you. If you are not using a Server side framework that can parse the incoming the request and map it to your DoSomethingWithRecipient function like PHP or ASP.NET than you your reinventing the wheel for no reason most likely.

Than with jQuery you simply perform an Ajax HTTP Post like so:

var recipient = {
  firstName: 'Fred',
  lastName: 'Johnson'
}

var json = JSON.stringify(recipient);

$.ajax({
    url: '/MyUrl/DoSomethingWithRecipient',
    type: 'POST',
    dataType: 'json',
    data: json,
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
    },
    error: function (result) {
    }
});
Community
  • 1
  • 1
Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
  • Why not keep the knowledge of the format of the template engine in the template engine...build the JSON in the template engine before posting – Brian Ogden Nov 13 '15 at 23:22
-2

This is what I am using:

_.forOwn(options, function(value, key) {
  if(key.indexOf('.') != -1){

    var split = key.split('.')

    if( !global[split[0]] ) {
      global[split[0]] = {}
    }

    global[split[0]][split[1]] = value
  }
});

Using global as I'm using NodeJS on the backend.

Seems to work so far, I'll report back on if I finally end up using it.

Anthony
  • 13,434
  • 14
  • 60
  • 80
  • Your approach is what needs fixed, google using Ajax with NodeJs: http://stackoverflow.com/questions/13478464/how-to-send-data-from-jquery-ajax-request-to-node-js-server – Brian Ogden Nov 13 '15 at 18:44