Created
March 7, 2016 00:20
-
-
Save niczak/fabee03a6f2e817bd227 to your computer and use it in GitHub Desktop.
Sort JS Object Alphabettically
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
// for OCD people or if an API requires this, in my case it was both | |
function sortObject(o) { | |
var sorted = {}, | |
key, a = []; | |
for (key in o) { | |
if (o.hasOwnProperty(key)) { | |
a.push(key); | |
} | |
} | |
a.sort(); | |
for (key = 0; key < a.length; key++) { | |
sorted[a[key]] = o[a[key]]; | |
} | |
return sorted; | |
} | |
var test = {}; | |
test.z = 'z'; | |
test.c = 'c'; | |
test.a = 'a'; | |
// z,c,a | |
console.dir(test); | |
test = sortObject(test); | |
// a,c,z | |
console.dir(test); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment