Matheus Hernandes Matheus Hernandes - 1 month ago 6
Javascript Question

Issues converting JS object to query string

I need to convert and JS object to query string and this object can wrap nested objects, like this:

var item = {
field1: 100,
field2: 200,
field3: [ 1,2,3 ],
field4: {
field5: 300,
field6: 'Quad',
field7: [ 4,5,6]
}
};


To convert this object I'm using this function

var serialize2 = function(obj, prefix) {
var str = [], p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize2(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
};


And once converted my query string looks like this


field4[field5]=300&field4[field6]=Quad


instead of


field4.field5=300&field4.field6=Quad


And then my Java Spring Application can't bind this children object

How can I solve this issue?

Answer

Just change your convert function:

var serialize2 = function(obj, prefix) {
    var str = [], p;
    for (p in obj) {
        if (obj.hasOwnProperty(p)) {
            var k;
            if (Array.isArray(obj)) {
                k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
            } else {
                k = prefix ? prefix + "." + p : p, v = obj[p];
            }
            str.push((v !== null && typeof v === "object") ?
                serialize2(v, k) :
            encodeURIComponent(k) + "=" + encodeURIComponent(v));
        }
    }
    return str.join("&");
};