diff --git a/lib/utils.js b/lib/utils.js index df572f3a..f72a0c94 100755 --- a/lib/utils.js +++ b/lib/utils.js @@ -26,29 +26,20 @@ exports.merge = function (target, source) { return target; } - if (Array.isArray(source)) { - for (var i = 0, il = source.length; i < il; ++i) { - if (typeof source[i] !== 'undefined') { - if (typeof target[i] === 'object') { - target[i] = exports.merge(target[i], source[i]); - } - else { - target[i] = source[i]; - } - } - } + if (typeof source !== 'object') { + target.push(source); + return target; + } + if (typeof target !== 'object') { + target = [target].concat(source); return target; } - if (Array.isArray(target)) { - if (typeof source !== 'object') { - target.push(source); - return target; - } - else { - target = exports.arrayToObject(target); - } + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target); } var keys = Object.keys(source); @@ -56,18 +47,11 @@ exports.merge = function (target, source) { var key = keys[k]; var value = source[key]; - if (value && - typeof value === 'object') { - - if (!target[key]) { - target[key] = value; - } - else { - target[key] = exports.merge(target[key], value); - } + if (!target[key]) { + target[key] = value; } else { - target[key] = value; + target[key] = exports.merge(target[key], value); } } diff --git a/test/parse.js b/test/parse.js index 8bed58bf..26bb564f 100755 --- a/test/parse.js +++ b/test/parse.js @@ -80,6 +80,17 @@ describe('parse()', function () { done(); }); + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + it('parses a nested array', function (done) { expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } });