Search code examples
javascriptjqueryarraysjsonjsonp

How to convert a form to a Json array in javascript


I am trying to convert a form result to this format below.

{
  "project": {
    "id": 5,
    "name": "max",
    "identifier": "max_project",
    "description": "This is description",
  }
}

But result is something like this,

{name: "max", identifier: "max_project", description: "This is description"}

Please help me to correct the code to get the intended result. I am trying to post the result in jsonp format.

$("#submit").on('click', function() {
  var data = {};

  $("#form").serializeArray().map(function(x) {
    data[x.name] = x.value;
  });
  console.log(data);
})
<form id="form" action="submit" method="post">
  Name:
  <input type="text" name="name">
  <br>identifier:
  <input type="text" name="identifier">
  <br>description:
  <textarea type="text" name="description"></textarea>
  <br>
  <input id="submit" type="button" name="submit" value="submit">
</form>


Solution

  • The simplest solution to achieve your result is the following

    $("#submit").on('click', function() {
      var data = {project:{}};
    
      $("#form").serializeArray().map(function(x) {
        data["project"][x.name] = x.value;
      });
      console.log(data);
    })
    

    Or the way you did it but and put it in another hash

    $("#submit").on('click', function() {
      var project = {};
    
      $("#form").serializeArray().map(function(x) {
        project[x.name] = x.value;
      });
      var data = {project: project}
      console.log(data);
    })
    

    There are many ways to achieve the same result