Skip to content

Instantly share code, notes, and snippets.

@niczak
Created March 7, 2016 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niczak/fabee03a6f2e817bd227 to your computer and use it in GitHub Desktop.
Save niczak/fabee03a6f2e817bd227 to your computer and use it in GitHub Desktop.
Sort JS Object Alphabettically
// 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