Daniel Cai Daniel Cai - 2 months ago 15
JSON Question

Generate JSON using jQuery

I have 4 inputs in a form:

<form id="mark_date_form">
<input type="text" name="title" class="form-control" placeholder="Title" value="motherday">
<input type="text" name="date" class="form-control datepick" placeholder="MM/DD" value="05/13">

<input type="text" name="title" class="form-control" placeholder="Title" value="fatherday">
<input type="text" name="date" class="form-control datepick " placeholder="MM/DD" value="06/18">
</form>


When I use
$('#mark_date_form').serializeArray()
in jQuery, it returns

[
{
"name": "title",
"value": "motherday"
},
{
"name": "date",
"value": "05/13"
},
{
"name": "title",
"value": "fatherday"
},
{
"name": "date",
"value": "06/18"
}
]


The question is I have to come out with something like this:

[
{
"title": "motherday",
"date": "05/13"
},
{
"title": "fatherday",
"date": "06/18"
}
]


What should be the jQuery looks like?

Thank you very much!

Answer

You can use this:

var a = [];
$('#mark_date_form input').each(function(){
    if($(this).attr('name')=='title'){
        a.push({"title":$(this).val(),"date":$(this).next().val()});
    }
});
console.log(a);

Output:

[Object { title="motherday",  date="05/13"}, Object { title="fatherday",  date="06/18"}]
Comments