Skip to content

Instantly share code, notes, and snippets.

@staxmanade
Created August 2, 2018 02:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save staxmanade/eddba7349cc6c5aed8c4389ce21a2fc4 to your computer and use it in GitHub Desktop.
Save staxmanade/eddba7349cc6c5aed8c4389ce21a2fc4 to your computer and use it in GitHub Desktop.
var recursivelyOrderKeys = function(unordered) {
// If it's an array - recursively order any
// dictionary items within the array
if (Array.isArray(unordered)) {
unordered.forEach(function (item, index) {
unordered[index] = recursivelyOrderKeys(item);
});
return unordered;
}
// If it's an object - let's order the keys
if (typeof unordered === 'object') {
var ordered = {};
Object.keys(unordered).sort().forEach(function(key) {
ordered[key] = recursivelyOrderKeys(unordered[key]);
});
return ordered;
}
return unordered;
};
var stringifyKeysInOrder = function(data) {
var sortedData = recursivelyOrderKeys(data);
return JSON.stringify(sortedData, null, ' ');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment