Skip to content

Commit 9ca1bf1

Browse files
authored
Merge pull request #58 from juanjoDiaz/feature/30/option_to_sort_properties
Option to sort properties
2 parents 1991813 + 7bd3bbc commit 9ca1bf1

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ Available configurations:
6565
##### Rendering Options
6666
* `useToJSON`: use the toJSON method to render an object as a string as available. Usefull for objects like Date or Mongo's ObjectID that migh make more sense as a strign than as empty objects. True by default.
6767

68+
* `sortPropertiesBy`: use the given sorting function to deeply sort the object properties.
69+
6870
#### `openAtDepth([depth])`
6971

7072
```js

demo/index.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ var complex = {
3030
number: 123,
3131
anObject: {
3232
a: 'b',
33-
c: 'd',
34-
e: 'f\"'
33+
e: 'd',
34+
c: 'f\"'
3535
},
3636
string: 'Hello World',
3737
url: 'https://github.com/mohsen1/json-formatter-js',
@@ -48,7 +48,8 @@ var examples = [
4848
{ title: 'Empty Object', json: Object.create(null) },
4949
{ title: 'Empty Array', json: [] },
5050
{ title: 'Deep', json: deep },
51-
{ title: 'Dark', json: complex, config: { theme: 'dark' } }
51+
{ title: 'Dark', json: complex, config: { theme: 'dark' } },
52+
{ title: 'Sorted Keys', json: complex, config: { sortPropertiesBy: (a, b) => a > b } }
5253
];
5354

5455
var result = document.querySelector('.result');

src/index.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export interface JSONFormatterConfiguration {
2626
animateClose?: boolean;
2727
theme?: string;
2828
useToJSON?: boolean;
29+
sortPropertiesBy?: (a: string, b: string) => number;
2930
};
3031

3132
const _defaultConfig: JSONFormatterConfiguration = {
@@ -35,7 +36,8 @@ const _defaultConfig: JSONFormatterConfiguration = {
3536
animateOpen: true,
3637
animateClose: true,
3738
theme: null,
38-
useToJSON: true
39+
useToJSON: true,
40+
sortPropertiesBy: null
3941
};
4042

4143

@@ -202,7 +204,10 @@ export default class JSONFormatter {
202204
*/
203205
private get keys(): string[] {
204206
if (this.isObject) {
205-
return Object.keys(this.json).map((key)=> key ? key : '""');
207+
const keys = Object.keys(this.json).map((key)=> key ? key : '""')
208+
return (!this.isArray && this.config.sortPropertiesBy)
209+
? keys.sort(this.config.sortPropertiesBy)
210+
: keys;
206211
} else {
207212
return [];
208213
}

0 commit comments

Comments
 (0)