Last active
February 21, 2025 07:45
-
-
Save deansimcox/4640a44fb56412cb12efd6626e71faa7 to your computer and use it in GitHub Desktop.
JS Sorting
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
const jsObjectToSort = {b: 2, c: {d: 4, a: 0}, a: 1}; | |
// Recursively sort js object keys | |
function sortObjectByKey(obj) { | |
let sortedObj = {}; | |
Object.keys(obj).sort().forEach(key => { | |
sortedObj[key] = (typeof obj[key] === 'object' && !Array.isArray(obj[key])) ? sortObjectByKey(obj[key]) : obj[key]; | |
}); | |
return sortedObj; | |
} | |
sortObjectByKey(jsObjectToSort); | |
// One-liner (not recursive) | |
Object.fromEntries(Object.entries(jsObjectToSort).sort()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment