If you need a recursive function that will produce proper URL parameters based on the object given, try my Coffee-Script one.
@toParams = (params) ->
pairs = []
do proc = (object=params, prefix=null) ->
for own key, value of object
if value instanceof Array
for el, i in value
proc(el, if prefix? then "#{prefix}[#{key}][]" else "#{key}[]")
else if value instanceof Object
if prefix?
prefix += "[#{key}]"
else
prefix = key
proc(value, prefix)
else
pairs.push(if prefix? then "#{prefix}[#{key}]=#{value}" else "#{key}=#{value}")
pairs.join('&')
or the JavaScript compiled...
toParams = function(params) {
var pairs, proc;
pairs = [];
(proc = function(object, prefix) {
var el, i, key, value, _results;
if (object == null) object = params;
if (prefix == null) prefix = null;
_results = [];
for (key in object) {
if (!__hasProp.call(object, key)) continue;
value = object[key];
if (value instanceof Array) {
_results.push((function() {
var _len, _results2;
_results2 = [];
for (i = 0, _len = value.length; i < _len; i++) {
el = value[i];
_results2.push(proc(el, prefix != null ? "" + prefix + "[" + key + "][]" : "" + key + "[]"));
}
return _results2;
})());
} else if (value instanceof Object) {
if (prefix != null) {
prefix += "[" + key + "]";
} else {
prefix = key;
}
_results.push(proc(value, prefix));
} else {
_results.push(pairs.push(prefix != null ? "" + prefix + "[" + key + "]=" + value : "" + key + "=" + value));
}
}
return _results;
})();
return pairs.join('&');
};
This will construct strings like so:
toParams({a: 'one', b: 'two', c: {x: 'eight', y: ['g','h','j'], z: {asdf: 'fdsa'}}})
"a=one&b=two&c[x]=eight&c[y][0]=g&c[y][1]=h&c[y][2]=j&c[y][z][asdf]=fdsa"