From d6f5c9c8b5fa5866785faefb9c91c277580dc0b9 Mon Sep 17 00:00:00 2001 From: Ivan Zverev Date: Mon, 27 May 2019 17:41:12 +0300 Subject: [PATCH] [New] `parse`: add `allowSparse` option for not collapsing arrays with missing indices Fixes #181. --- lib/parse.js | 6 ++++++ test/.eslintrc | 1 + test/parse.js | 8 ++++++++ 3 files changed, 15 insertions(+) diff --git a/lib/parse.js b/lib/parse.js index 057adc85..5f697c1c 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -7,6 +7,7 @@ var has = Object.prototype.hasOwnProperty; var defaults = { allowDots: false, allowPrototypes: false, + allowSparse: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, @@ -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, @@ -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); }; diff --git a/test/.eslintrc b/test/.eslintrc index f76d573c..4879a61a 100644 --- a/test/.eslintrc +++ b/test/.eslintrc @@ -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 } diff --git a/test/parse.js b/test/parse.js index 397b867d..790bf572 100644 --- a/test/parse.js +++ b/test/parse.js @@ -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' } });