From 5e5cec0e265e5b2c2a3c7a8a7cfa23db1b29a701 Mon Sep 17 00:00:00 2001 From: PhilippeChab Date: Mon, 1 Oct 2018 23:35:58 -0400 Subject: [PATCH] Support arrays format in query --- index.js | 26 +++++++++++++++++++++++++- test.js | 14 ++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 7685d74..7b6973c 100644 --- a/index.js +++ b/index.js @@ -54,8 +54,32 @@ QueryString.prototype.parse = function (queryStr) { queryStr.split('&').forEach((param) => { const components = param.split('='); + const value = decodeURIComponent(components[1]); + var key = decodeURIComponent(components[0]); - obj[decodeURIComponent(components[0])] = decodeURIComponent(components[1]); + //Is the query param an array? + if (key.search(/\[([0-9]*)\]/) !== -1) { + const indexOfArray = key.slice(-2) !== '[]' ? key.charAt(key.length - 2) : undefined; + key = key.slice(0, key.indexOf('[')); + + //Does the array already exist in the object + if (obj[key]) { + if (indexOfArray) { + obj[key][indexOfArray] = value; + } else { + obj[key].push(value); + } + } else { + if (indexOfArray) { + obj[key] = []; + obj[key][indexOfArray] = value; + } else { + obj[key] = [value]; + } + } + } else { + obj[key] = value; + } }); return obj; diff --git a/test.js b/test.js index 246be2e..163301d 100644 --- a/test.js +++ b/test.js @@ -45,5 +45,19 @@ describe('query-stringifier', function () { expect(parsed).to.have.property('foo', 'bar'); expect(parsed).to.have.property('thing', 'thung'); }); + it('converts an query string with arrays', function () { + var parsed = qs.parse('&arr[]=1&arr[]=2&arr[]=3'); + + expect(parsed).to.be.an('object'); + expect(parsed).to.have.keys(['arr']); + expect(parsed).to.deep.equal({ arr: ['1', '2', '3'] }); + }); + it('converts an query string with arrays and indexes', function () { + var parsed = qs.parse('&arr[2]=1&arr[0]=2&arr[1]=3'); + + expect(parsed).to.be.an('object'); + expect(parsed).to.have.keys(['arr']); + expect(parsed).to.deep.equal({ arr: ['2', '3', '1'] }); + }); }); }); \ No newline at end of file