Skip to content

Commit 05c05d0

Browse files
authored
Merge pull request #10 from PhilippeChab/Support_Arrays_In_Parse
Support arrays format in query
2 parents 0899624 + 5e5cec0 commit 05c05d0

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

index.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,32 @@ QueryString.prototype.parse = function (queryStr) {
5454

5555
queryStr.split('&').forEach((param) => {
5656
const components = param.split('=');
57+
const value = decodeURIComponent(components[1]);
58+
var key = decodeURIComponent(components[0]);
5759

58-
obj[decodeURIComponent(components[0])] = decodeURIComponent(components[1]);
60+
//Is the query param an array?
61+
if (key.search(/\[([0-9]*)\]/) !== -1) {
62+
const indexOfArray = key.slice(-2) !== '[]' ? key.charAt(key.length - 2) : undefined;
63+
key = key.slice(0, key.indexOf('['));
64+
65+
//Does the array already exist in the object
66+
if (obj[key]) {
67+
if (indexOfArray) {
68+
obj[key][indexOfArray] = value;
69+
} else {
70+
obj[key].push(value);
71+
}
72+
} else {
73+
if (indexOfArray) {
74+
obj[key] = [];
75+
obj[key][indexOfArray] = value;
76+
} else {
77+
obj[key] = [value];
78+
}
79+
}
80+
} else {
81+
obj[key] = value;
82+
}
5983
});
6084

6185
return obj;

test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,20 @@ describe('query-stringifier', function () {
4545
expect(parsed).to.have.property('foo', 'bar');
4646
expect(parsed).to.have.property('thing', 'thung');
4747
});
48+
it('converts an query string with arrays', function () {
49+
var parsed = qs.parse('&arr[]=1&arr[]=2&arr[]=3');
50+
51+
expect(parsed).to.be.an('object');
52+
expect(parsed).to.have.keys(['arr']);
53+
expect(parsed).to.deep.equal({ arr: ['1', '2', '3'] });
54+
});
55+
it('converts an query string with arrays and indexes', function () {
56+
var parsed = qs.parse('&arr[2]=1&arr[0]=2&arr[1]=3');
57+
58+
expect(parsed).to.be.an('object');
59+
expect(parsed).to.have.keys(['arr']);
60+
expect(parsed).to.deep.equal({ arr: ['2', '3', '1'] });
61+
});
4862
});
4963

5064
describe('#extract', function () {

0 commit comments

Comments
 (0)