I need to sort JavaScript objects based on key length
Hence the following:
{ 'b' : 'asdsad', 'bbb' : 'masdas', 'bb' : 'dsfdsfsdf' }
Would become:
{ 'b' : 'dsfdsfsdf', 'bb' : 'dsfdsfsdf', 'bbb' : 'masdas' }
I need to sort JavaScript objects based on key length
Hence the following:
{ 'b' : 'asdsad', 'bbb' : 'masdas', 'bb' : 'dsfdsfsdf' }
Would become:
{ 'b' : 'dsfdsfsdf', 'bb' : 'dsfdsfsdf', 'bbb' : 'masdas' }
There is no such concept as order for Javascript object properties, you can't sort them and then try to get by declaring order. Because there is no guarantee in which order they will appear.
From the EcmaScript 1 specification
4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties which contain primitive values, objects, or functions. A function stored in the property of an object is called a method.
If you need ordering, maybe it will be useful to look arrays.
function TestA() {
var a = {
'b': 'asdsad',
'bbb': 'masdas',
'bb': 'dsfdsfsdf'
}
var keyArray = Object.keys(a);
var object = {};
keyArray.sort();
keyArray.forEach(function(item) {
object[item] = a[item]
})
return object
}