Question

Was wondering what I'd have to do to convert my data that is currently being sent like this (using serializeArray())

data[0][name]:title
data[0][value]:This is my sample title
data[1][name]:description
data[1][value]:This is an (optional) description but I'm filling it out as an example
data[2][name]:source
data[2][value]:http://www.cnn.com
data[3][name]:category
data[3][value]:animals

To send like this instead:

data[title]:This is my sample title
data[description:This is an (optional) description but I'm filling it out as an example
data[source]:http://www.cnn.com
data[category]:animals

Code:

$(function() {
    $('input[type="submit"]').click(function() {
        var $data = $('#js-serialize').serializeArray();
        console.log($data);
        $.post('/echo/json', {
            'data': $data
        }, function(data) {
            console.log(data);
        }, 'json');
        return false;

    });

});

<form id="js-serialize">
<input name="title" placeholder="title" />
<input name="description" placeholder="description" />
<input name="source" placeholder="source" />
<input name="category" placeholder="category"/>
<input type="submit" name="submit" />
</form>​

Demo:

http://jsfiddle.net/someprimetime/bnPwN/5/

Was it helpful?

Solution

It seems that you're looking for an object representation instead of an array.

jQuery does not support something like serializeObject() out of the box. This plugin, however, seems to do exactly what you want.

OTHER TIPS

Not tested, but:

function serializeObject(serializedArray){
    var serializedObj={};
    serializedArray.forEach(function(i){
       serializedObj[i.name]=i.value;       
    });
    return serializedObj;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top