Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'] });
});
});
});