Skip to content

Instantly share code, notes, and snippets.

@adamterlson
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamterlson/a051f8ebb0e66b45010b to your computer and use it in GitHub Desktop.
Save adamterlson/a051f8ebb0e66b45010b to your computer and use it in GitHub Desktop.
Ordering JSON document properties alphabetically
function sortProperties(objToSort) {
var properties = Object.keys(objToSort).sort();
var result = {};
properties.forEach(function (prop) {
if (!objToSort[prop]) {
result[prop] = objToSort[prop];
}
else if (Array.isArray(objToSort[prop])){
result[prop] = objToSort[prop].map(sortProperties);
}
else if (typeof objToSort[prop] === 'object') {
result[prop] = sortProperties(objToSort[prop]);
}
else {
result[prop] = objToSort[prop];
}
});
return result;
}
['./jsonFile'].forEach(function (location) {
console.log(location, JSON.stringify(sortProperties(require(location)), null, 2));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment