Skip to content

Commit

Permalink
[New] parse: add allowSparse option for not collapsing arrays wit…
Browse files Browse the repository at this point in the history
…h missing indices

Fixes #181.
  • Loading branch information
Ivan Zverev authored and ljharb committed May 27, 2019
1 parent d1d06a6 commit d6f5c9c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/parse.js
Expand Up @@ -7,6 +7,7 @@ var has = Object.prototype.hasOwnProperty;
var defaults = {
allowDots: false,
allowPrototypes: false,
allowSparse: false,
arrayLimit: 20,
charset: 'utf-8',
charsetSentinel: false,
Expand Down Expand Up @@ -203,6 +204,7 @@ var normalizeParseOptions = function normalizeParseOptions(opts) {
return {
allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
Expand Down Expand Up @@ -239,5 +241,9 @@ module.exports = function (str, opts) {
obj = utils.merge(obj, newObj, options);
}

if (options.allowSparse === true) {
return obj;
}

return utils.compact(obj);
};
1 change: 1 addition & 0 deletions test/.eslintrc
Expand Up @@ -11,6 +11,7 @@
"no-buffer-constructor": 0,
"no-extend-native": 0,
"no-magic-numbers": 0,
"no-sparse-arrays": 0,
"object-curly-newline": 0,
"sort-keys": 0
}
Expand Down
8 changes: 8 additions & 0 deletions test/parse.js
Expand Up @@ -237,6 +237,14 @@ test('parse()', function (t) {
st.end();
});

t.test('parses sparse arrays', function (st) {
st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] });
st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] });
st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] });
st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] });
st.end();
});

t.test('parses semi-parsed strings', function (st) {
st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } });
st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } });
Expand Down

0 comments on commit d6f5c9c

Please sign in to comment.