Manoj Masakorala
Manoj Masakorala

Reputation: 446

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>

Upvotes: 1

Views: 2325

Answers (2)

hgh
hgh

Reputation: 51

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?

Upvotes: 1

Omar Mowafi
Omar Mowafi

Reputation: 854

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

Upvotes: 1

Related Questions