Skip to content
Closed
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
17 changes: 14 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,12 @@ function parserForArrayFormat(options) {
}

if (accumulator[key] === undefined) {
accumulator[key] = [value];
if (options.allowEmptyArrays) {
accumulator[key] = [];
} else {
accumulator[key] = [value];
}

return;
}

Expand Down Expand Up @@ -197,7 +202,8 @@ function parse(input, options) {
sort: true,
arrayFormat: 'none',
parseNumbers: false,
parseBooleans: false
parseBooleans: false,
allowEmptyArrays: false
}, options);

const formatter = parserForArrayFormat(options);
Expand Down Expand Up @@ -263,7 +269,8 @@ exports.stringify = (object, options) => {
options = Object.assign({
encode: true,
strict: true,
arrayFormat: 'none'
arrayFormat: 'none',
allowEmptyArrays: false
}, options);

const formatter = encoderForArrayFormat(options);
Expand Down Expand Up @@ -295,6 +302,10 @@ exports.stringify = (object, options) => {
}

if (Array.isArray(value)) {
if (options.allowEmptyArrays && value.length === 0) {
return key + '[]=';
}

return value
.reduce(formatter(key), [])
.join('&');
Expand Down
6 changes: 6 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,9 @@ test('query strings having comma encoded and format option as `comma`', t => {
]
});
});

test('should decode empty arrays when allowEmptyArrays is set', t => {
t.deepEqual(queryString.parse('a[]=', {allowEmptyArrays: true, arrayFormat: 'bracket'}), {
a: []
});
});
4 changes: 4 additions & 0 deletions test/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,3 +259,7 @@ test('should ignore both null and undefined when skipNull is set for arrayFormat
arrayFormat: 'index'
}), 'a[0]=1&a[1]=2&c=1');
});

test('should encode empty arrays when allowEmptyArrays is set', t => {
t.is(queryString.stringify({a: []}, {allowEmptyArrays: true, arrayFormat: 'bracket'}), 'a[]=');
});