Created
February 11, 2014 15:50
-
-
Save nazywamsiepawel/8937544 to your computer and use it in GitHub Desktop.
Recursively sort object keys
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
var _ = require('underscore'); | |
function sortObject(obj){ | |
var oNew = {}; | |
if(typeof obj === 'object'){ | |
var aKeys = _.keys(obj); | |
aKeys.sort(); | |
_.each(aKeys, function(sKey, oVal){ | |
oNew[sKey] = sortObject(obj[sKey]); | |
}); | |
} else { | |
return obj; | |
}; | |
return oNew; | |
} | |
var a = { | |
z : 123, | |
b : 1, | |
g : 2, | |
c: { | |
l:1, | |
a:2 | |
} | |
} | |
a = sortObject(a); | |
console.log(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment