Flatten a javascript object to pass as querystring

Saxman picture Saxman · Mar 31, 2011 · Viewed 51.1k times · Source

I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:

{ cost: 12345, insertBy: 'testUser' } would become cost=12345&insertBy=testUser

I can't use jQuery AJAX call for this call, I know we can use that and pass the object in as data but not in this case. Using jQuery to flatten to object would be okay though.

Thank you.

Answer

Tim Down picture Tim Down · Mar 31, 2011

Here's a non-jQuery version:

function toQueryString(obj) {
    var parts = [];
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
        }
    }
    return parts.join("&");
}