1 # Get a Version of an Object with Sorted Keys
3 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.
5 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.
7 **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.
10 var sortedObject = require("sorted-object");
12 var objectToSerialize = generateStuffNondeterministically();
15 fs.writeFileSync("dest.json", JSON.stringify(objectToSerialize));
18 var sortedVersion = sortedObject(objectToSerialize);
19 fs.writeFileSync("dest.json", JSON.stringify(sortedVersion));