Skip to content
Advertisement

How to serialize an Object into a list of URL query parameters?

Without knowing the keys of a JavaScript Object, how can I turn something like…

var obj = {
   param1: 'something',
   param2: 'somethingelse',
   param3: 'another'
}

obj[param4] = 'yetanother';

…into…

var str = 'param1=something&param2=somethingelse&param3=another&param4=yetanother';

…?

Advertisement

Answer

var str = "";
for (var key in obj) {
    if (str != "") {
        str += "&";
    }
    str += key + "=" + encodeURIComponent(obj[key]);
}

Example: http://jsfiddle.net/WFPen/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement