Skip to content

Instantly share code, notes, and snippets.

@davemo
Created June 11, 2013 17:03
Show Gist options
  • Save davemo/5758664 to your computer and use it in GitHub Desktop.
Save davemo/5758664 to your computer and use it in GitHub Desktop.
A utility to convert JS objects to Form Encoded strings
var jsToFormEncoded = function(obj) {
var fullSubName, i, innerObj, name, query, subName, subValue, value;
query = "";
name = void 0;
value = void 0;
fullSubName = void 0;
subValue = void 0;
innerObj = void 0;
i = void 0;
for (name in obj) {
value = obj[name];
if (value instanceof Array) {
i = 0;
while (i < value.length) {
subValue = value[i];
fullSubName = name + "[" + i + "]";
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + "&";
++i;
}
} else if (value instanceof Object) {
for (subName in value) {
subValue = value[subName];
fullSubName = name + "[" + subName + "]";
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + "&";
}
} else {
if (value !== undefined && value !== null) {
query += encodeURIComponent(name) + "=" + encodeURIComponent(value) + "&";
}
}
}
if (query.length) {
return query.substr(0, query.length - 1);
} else {
return query;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment