Skip to content

Instantly share code, notes, and snippets.

@dgs700
Created January 30, 2013 22:39
Show Gist options
  • Save dgs700/4677933 to your computer and use it in GitHub Desktop.
Save dgs700/4677933 to your computer and use it in GitHub Desktop.
Javascript object to URL encoded query string converter. Code extracted from jQuery.param() and boiled down to bare metal js. Should handle deep/nested objects and arrays in the same manner as jQuery's ajax functionality.
var objectToQueryString = function (a) {
var prefix, s, add, name, r20, output;
s = [];
r20 = /%20/g;
add = function (key, value) {
// If value is a function, invoke it and return its value
value = ( typeof value == 'function' ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
if (a instanceof Array) {
for (name in a) {
add(name, a[name]);
}
} else {
for (prefix in a) {
buildParams(prefix, a[ prefix ], add);
}
}
output = s.join("&").replace(r20, "+");
return output;
};
function buildParams(prefix, obj, add) {
var name, i, l, rbracket;
rbracket = /\[\]$/;
if (obj instanceof Array) {
for (i = 0, l = obj.length; i < l; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(prefix + "[" + ( typeof obj[i] === "object" ? i : "" ) + "]", obj[i], add);
}
}
} else if (typeof obj == "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "[" + name + "]", obj[ name ], add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}
@yairEO
Copy link

yairEO commented Feb 5, 2021

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment