Last active
December 11, 2024 11:41
-
-
Save TokaLazy/5127d027dbcdcbc85e188b1c8a379980 to your computer and use it in GitHub Desktop.
Deep Sort Javascript Object (ESNext)
This file contains hidden or 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 sortObject(object) { | |
// object is not defined (empty string, null, zero, undefined) | |
if (!object) { | |
return object | |
} | |
// object is an array | |
if (object instanceof Array) { | |
if (typeof object[0] === 'object') { | |
return object.map(item => sortObject(item)) | |
} | |
return object.sort((a,b) => String(a).localeCompare(String(b))) | |
} | |
// 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] | |
console.log('next', object[key]) | |
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