diff --git a/test/util.strings.js b/test/util.strings.js index c7c0b10..a88c5e3 100644 --- a/test/util.strings.js +++ b/test/util.strings.js @@ -43,6 +43,9 @@ $(document).ready(function() { var obj = {'foo&bar': 'baz', 'test': 'total success', 'nested': {'works': 'too'}, 'isn\'t': ['that', 'cool?']}; assert.equal(_.toQuery(obj), 'foo%26bar=baz&test=total%20success&nested%5Bworks%5D=too&isn\'t%5B%5D=that&isn\'t%5B%5D=cool%3F', 'can convert a hash to a query string'); assert.equal(_.toQuery(obj), jQuery.param(obj), 'query serialization matchs jQuery.param()'); + assert.equal(_.toQuery({a: []}), '', 'empty array params produce the empty string'); + assert.equal(_.toQuery({a: [], b: []}), '', 'multiple empty array params do not lead to spurious ampersands'); + assert.equal(_.toQuery({a: null, b: undefined}), 'a=null&b=undefined', 'respects null and undefined'); }); QUnit.test('strContains', function(assert) { diff --git a/underscore.util.strings.js b/underscore.util.strings.js index b7384c1..291c26a 100644 --- a/underscore.util.strings.js +++ b/underscore.util.strings.js @@ -29,13 +29,13 @@ var buildParams = function(prefix, val, top) { if (_.isUndefined(top)) top = true; if (_.isArray(val)) { - return _.map(val, function(value, key) { + return _.compact(_.map(val, function(value, key) { return buildParams(top ? key : prefix + '[]', value, false); - }).join('&'); + })).join('&'); } else if (_.isObject(val)) { - return _.map(val, function(value, key) { + return _.compact(_.map(val, function(value, key) { return buildParams(top ? key : prefix + '[' + key + ']', value, false); - }).join('&'); + })).join('&'); } else { return urlEncode(prefix) + '=' + urlEncode(val); }