Skip to content

Instantly share code, notes, and snippets.

@TokaLazy
Last active August 23, 2024 07:56
Show Gist options
  • Save TokaLazy/5127d027dbcdcbc85e188b1c8a379980 to your computer and use it in GitHub Desktop.
Save TokaLazy/5127d027dbcdcbc85e188b1c8a379980 to your computer and use it in GitHub Desktop.
Deep Sort Javascript Object (ESNext)
function sortObject(object) {
// object is not defined (empty string, null, zero, undefined)
if (!object) {
return object
}
// object is an array
if (object instanceof Array) {
return object.map(item => sortObject(item))
}
// it is not an object
if (typeof object !== 'object') {
return object
}
const sortedObj = {}
const keys = Object.keys(object).sort((key1, key2) => key1.localeCompare(key2))
for (let index in keys) {
const key = keys[index]
sortedObj[key] = sortObject(object[key])
}
return sortedObj
}
// Thanks https://gist.github.com/ninapavlich/1697bcc107052f5b884a794d307845fe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment