Skip to content

Commit 334152b

Browse files
msn0sindresorhus
authored andcommitted
Add sort option (#107)
1 parent 6404fd9 commit 334152b

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

index.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,9 +176,13 @@ exports.stringify = function (obj, opts) {
176176

177177
opts = objectAssign(defaults, opts);
178178

179+
if (opts.sort === false) {
180+
opts.sort = function () {};
181+
}
182+
179183
var formatter = encoderForArrayFormat(opts);
180184

181-
return obj ? Object.keys(obj).sort().map(function (key) {
185+
return obj ? Object.keys(obj).sort(opts.sort).map(function (key) {
182186
var val = obj[key];
183187

184188
if (val === undefined) {

readme.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,31 @@ queryString.stringify({foo: [1,2,3]});
133133
// => foo=1&foo=2&foo=3
134134
```
135135

136+
#### sort
137+
138+
Type: `Function` `boolean`
139+
140+
Supports both `Function` as a custom sorting function or `false` for disabling sorting.
141+
142+
- `Function`:
143+
144+
```js
145+
const order = ['c', 'a', 'b'];
146+
queryString.stringify({ a: 1, b: 2, c: 3}, {
147+
sort: (m, n) => order.indexOf(m) >= order.indexOf(n)
148+
});
149+
// => 'c=3&a=1&b=2'
150+
```
151+
152+
- `false`:
153+
154+
```js
155+
queryString.stringify({ b: 1, c: 2, a: 3}, {sort: false});
156+
// => 'c=3&a=1&b=2'
157+
```
158+
159+
If omitted, keys are sorted using `Array#sort`, which means, converting them to strings and comparing strings in Unicode code point order.
160+
136161
### .extract(*string*)
137162

138163
Extract a query string from a URL that can be passed into `.parse()`.

test/stringify.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,3 +122,20 @@ test('array stringify representation with array indexes and sparse array', t =>
122122
a[10] = 'three';
123123
t.is(fn.stringify({bar: a}, {arrayFormat: 'index'}), 'bar[0]=one&bar[1]=two&bar[2]=three');
124124
});
125+
126+
test('should sort keys in given order', t => {
127+
const order = ['c', 'a', 'b'];
128+
const sort = (key1, key2) => order.indexOf(key1) >= order.indexOf(key2);
129+
130+
t.is(fn.stringify({a: 'foo', b: 'bar', c: 'baz'}, {sort}), 'c=baz&a=foo&b=bar');
131+
});
132+
133+
test('should disable sorting', t => {
134+
t.is(fn.stringify({
135+
c: 'foo',
136+
b: 'bar',
137+
a: 'baz'
138+
}, {
139+
sort: false
140+
}), 'c=foo&b=bar&a=baz');
141+
});

0 commit comments

Comments
 (0)