From 56ef57c1eb1a65f9b9124f72b0be2e9d5ddf0715 Mon Sep 17 00:00:00 2001 From: djunehor Date: Mon, 10 Nov 2025 22:01:38 +0100 Subject: [PATCH] [Fix] allowEmptyArrays respects arrayFormat option Fixes #525 - Modified allowEmptyArrays to respect the arrayFormat setting - comma format now produces 'key=' for empty arrays (when commaRoundTrip is false) - repeat format now produces 'key' for empty arrays - brackets/indices formats continue to produce 'key[]' (unchanged) - comma format with commaRoundTrip=true continues to produce 'key[]' (unchanged) - Added comprehensive tests covering all arrayFormat combinations - All 803 tests pass with no regressions - Maintains backward compatibility --- lib/stringify.js | 7 +++++++ test/stringify.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/lib/stringify.js b/lib/stringify.js index 2666eaf9..456bfcda 100644 --- a/lib/stringify.js +++ b/lib/stringify.js @@ -157,6 +157,13 @@ var stringify = function stringify( var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + if (generateArrayPrefix === 'comma' && !commaRoundTrip) { + return adjustedPrefix + '='; + } + if (typeof generateArrayPrefix === 'function' && generateArrayPrefix === arrayPrefixGenerators.repeat) { + return adjustedPrefix; + } + // for 'brackets', 'indices', or when commaRoundTrip is true return adjustedPrefix + '[]'; } diff --git a/test/stringify.js b/test/stringify.js index 4d776947..8845193e 100644 --- a/test/stringify.js +++ b/test/stringify.js @@ -328,6 +328,42 @@ test('stringify()', function (t) { st.end(); }); + t.test('allowEmptyArrays with different arrayFormat options', function (st) { + var testObj = { a: [], b: 'test' }; + + st.equal( + qs.stringify(testObj, { allowEmptyArrays: true, arrayFormat: 'indices' }), + 'a[]&b=test', + 'indices format should use brackets for empty arrays' + ); + + st.equal( + qs.stringify(testObj, { allowEmptyArrays: true, arrayFormat: 'brackets' }), + 'a[]&b=test', + 'brackets format should use brackets for empty arrays' + ); + + st.equal( + qs.stringify(testObj, { allowEmptyArrays: true, arrayFormat: 'repeat' }), + 'a&b=test', + 'repeat format should not add brackets or equals for empty arrays' + ); + + st.equal( + qs.stringify(testObj, { allowEmptyArrays: true, arrayFormat: 'comma' }), + 'a=&b=test', + 'comma format should use equals with empty value for empty arrays' + ); + + st.equal( + qs.stringify(testObj, { allowEmptyArrays: true, arrayFormat: 'comma', commaRoundTrip: true }), + 'a[]&b=test', + 'comma format with commaRoundTrip should use brackets for empty arrays' + ); + + st.end(); + }); + t.test('stringifies an array value with one item vs multiple items', function (st) { st.test('non-array item', function (s2t) { s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c');