Skip to content

Instantly share code, notes, and snippets.

@davidfurlong
davidfurlong / JSON.stringify-replacer-sort-keys.js
Last active May 5, 2024 06:00
JSON.stringify replacer function for having object keys sorted in output (supports deeply nested objects)
// Spec http://www.ecma-international.org/ecma-262/6.0/#sec-json.stringify
const replacer = (key, value) =>
value instanceof Object && !(value instanceof Array) ?
Object.keys(value)
.sort()
.reduce((sorted, key) => {
sorted[key] = value[key];
return sorted
}, {}) :
value;