Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if they're equal then it has to be a function; if they aren't, it must not be. also here, it'd be better to check the actual passed arrayFormat, rather than relying on function identity.

return adjustedPrefix;
}
// for 'brackets', 'indices', or when commaRoundTrip is true
return adjustedPrefix + '[]';
}

Expand Down
36 changes: 36 additions & 0 deletions test/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down