1

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>
Manoj Masakorala
  • 446
  • 1
  • 6
  • 20
  • Possible duplicate of [jQuery serializeArray not picking up dynamically created form elements](http://stackoverflow.com/questions/3626384/jquery-serializearray-not-picking-up-dynamically-created-form-elements) – diziaq Dec 05 '15 at 11:25

2 Answers2

1

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

Omar Mowafi
  • 854
  • 5
  • 13
1

in JavaScript, you have arrays and objects, the difference between arrays and objects are in the index of them, the array accepts just integer indexes and the objects accept strings.

by this, you can't have something like that you want.

the question is why?! why do you want that format?

hgh
  • 51
  • 6