Skip to content

Commit

Permalink
Issue #181 Added option for collapsing arrays with missing indices
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Zverev authored and ljharb committed May 27, 2019
1 parent da6d249 commit 23c4391
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -227,6 +227,13 @@ var noSparse = qs.parse('a[1]=b&a[15]=c');
assert.deepEqual(noSparse, { a: ['b', 'c'] });
```

You may also use `allowSparse` option to parse sparse arrays:

```javascript
var sparseArray = qs.parse('a[1]=2&a[3]=5', { allowSparse: true });
assert.deepEqual(sparseArray, { a: [, '2', , '5'] });
```

Note that an empty string is also a value, and will be preserved:

```javascript
Expand Down
6 changes: 6 additions & 0 deletions lib/parse.js
Expand Up @@ -8,6 +8,7 @@ var isArray = Array.isArray;
var defaults = {
allowDots: false,
allowPrototypes: false,
allowSparse: false,
arrayLimit: 20,
charset: 'utf-8',
charsetSentinel: false,
Expand Down Expand Up @@ -217,6 +218,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 @@ -253,5 +255,9 @@ module.exports = function (str, opts) {
obj = utils.merge(obj, newObj, options);
}

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

return utils.compact(obj);
};
8 changes: 8 additions & 0 deletions test/parse.js
Expand Up @@ -269,6 +269,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 23c4391

Please sign in to comment.