Search code examples
javascriptjqueryjsonpjson

How to modify this json object


How do i modify this code to get the intended outcome.

This is what i get from this code.

{"name":"abc","identifier":"abc_one","number":"55","description":"This is a description"}

But i want a json object like this,

{"project":  
  {"name":"abc",
   "identifier":"abc_one",
   "number":"55",
   "description":"This is a description"}
}

Please look at the code i have at the moment. It Need to be warped by a another object call "project".

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});
<form action="" method="post">
First Name:<input type="text" name="name" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="identifier" maxlength="36" size="12"/> <br/>
number:<input type="number" name="number" maxlength="36" size="12"/> <br/>
<textarea wrap="physical" cols="20" name="description" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<p><input type="submit" /></p>
</form>


Solution

  • All you need to change is following

    return o;
    

    To

    return {"project":o}
    

    in serializeObject function.