https://github.com/domenic/sorted-object
Returns a copy of an object with its keys sorted
https://github.com/domenic/sorted-object
Last synced: about 1 year ago
JSON representation
Returns a copy of an object with its keys sorted
- Host: GitHub
- URL: https://github.com/domenic/sorted-object
- Owner: domenic
- License: other
- Created: 2014-02-17T20:10:57.000Z (about 12 years ago)
- Default Branch: master
- Last Pushed: 2020-11-06T07:30:44.000Z (over 5 years ago)
- Last Synced: 2025-04-02T07:51:09.385Z (about 1 year ago)
- Language: JavaScript
- Size: 7.81 KB
- Stars: 35
- Watchers: 3
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
- awesome-micro-npm-packages - sorted-object - Returns a copy of an object with its keys sorted. (Modules / Object)
- awesome-micro-npm-packages-zh - sorted-object - 返回一个对象的拷贝,并对其键进行排序. (模块 / 对象)
- awesome-micro-npm-packages - sorted-object - Returns a copy of an object with its keys sorted. (Modules / Object)
- fucking-awesome-micro-npm-packages - sorted-object - Returns a copy of an object with its keys sorted. (Modules / Object)
README
# Get a Version of an Object with Sorted Keys
Although objects in JavaScript are theoretically unsorted, in practice most engines use insertion order—at least, ignoring numeric keys. This manifests itself most prominently when dealing with an object's JSON serialization.
So, for example, you might be trying to serialize some object to a JSON file. But every time you write it, it ends up being output in a different order, depending on how you created it in the first place! This makes for some ugly diffs.
**sorted-object** gives you the answer. Just use this package to create a version of your object with its keys sorted before serializing, and you'll get a consistent order every time.
```js
var sortedObject = require("sorted-object");
var objectToSerialize = generateStuffNondeterministically();
// Before:
fs.writeFileSync("dest.json", JSON.stringify(objectToSerialize));
// After:
var sortedVersion = sortedObject(objectToSerialize);
fs.writeFileSync("dest.json", JSON.stringify(sortedVersion));
```