Skip to content

Commit

Permalink
Add key sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
mnaoumov committed Jan 13, 2025
1 parent 9254288 commit f0b1045
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ export interface ToJsonOptions {
* Defaults to `false`.
*/
shouldHandleUndefined: boolean;
/**
* Specifies whether to sort the keys of the JSON output.
* Defaults to `false`.
*/
shouldSortKeys: boolean;
/**
* Specifies the indentation of the JSON output. This can be a number of spaces or a string. Defaults to `2`.
*/
Expand Down Expand Up @@ -281,6 +286,7 @@ export function toJson(value: unknown, options: Partial<ToJsonOptions> = {}): st
maxDepth: -1,
shouldHandleCircularReferences: false,
shouldHandleUndefined: false,
shouldSortKeys: false,
space: 2
};

Expand Down Expand Up @@ -339,6 +345,10 @@ export function toJson(value: unknown, options: Partial<ToJsonOptions> = {}): st
}
objectDepthMap.set(property, depth + 1);
}

if (fullOptions.shouldSortKeys) {
return Object.fromEntries(Object.entries(value).sort(([key1], [key2]) => key1.localeCompare(key2)));
}
}

return value as JSONValueF<unknown>;
Expand Down

0 comments on commit f0b1045

Please sign in to comment.