Last active
August 29, 2015 14:07
-
-
Save adamterlson/a051f8ebb0e66b45010b to your computer and use it in GitHub Desktop.
Ordering JSON document properties alphabetically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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