S
S
semolex2014-06-20 11:42:56
JavaScript
semolex, 2014-06-20 11:42:56

How to clear JSON data received by .serializeArray() method?

Hello!
There is a problem of the following content.
I have an html form. There is this code:

$( "form" ).submit(function( event ) {
        console.log(JSON.stringify($(this).serializeArray()));
        var arr = $( "form" ).serializeArray();
        $.ajax({
            type: "POST",
            url: "make_order",
            // Tut pizdos
            data: JSON.stringify(arr),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){alert(test);},
            failure: function(errMsg) {
            alert(errMsg);
    }
});
        event.preventDefault();
});


As a result, I get this JSON:
[{"name":"assigment","value":"1"},{"name":"subject","value":""},{"name":"title","value":""},{"name":"description","value":""},{"name":"`pages","value":""},{"name":"sources`","value":""},{"name":"id_writer","value":""},{"name":"discount_code`","value":""},{"name":"email","value":""}]


And I need to get JSON in a simplified form key value, like:
{"assignment" : "1" } , {"subject":"2"}...
Is it possible to do this in regular ways?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Melnikov, 2014-06-20
@semolex

/*
data - полученный ответ от сервера
*/ 
var result = [];
for (var i = 0; i < data.length; i++) {
  var obj = {};
  obj[data[i].name] = data[i].value;
  result.push(obj);
}
console.log(result); 
// результат
/* [{"assigment":"1"},{"subject":""},{"title":""},{"description":""},{"`pages":""},{"sources`":""},{"id_writer":""},{"discount_code`":""},{"email":""}]  */

D
Denis Ineshin, 2014-06-20
@IonDen

You can add your method to jQuery and safely use it later:

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();

    $.each(a, function () {
        if (o[this.name]) {
            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;
};

Will return the data in the form of the object you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question