Problem description
I need to sort the JavaScript objects by key.
So the following:
‘b‘ : ‘asdsad‘, ‘c‘ : ‘masdas‘, ‘a‘ : ‘dsfdsfsdf‘ }
will become:
‘a‘ : ‘dsfdsfsdf‘, ‘b‘ : ‘asdsad‘, ‘c‘ : ‘masdas‘ }
The best solution
method One if you want to iterate over the properties of an object, you can sort the keys and then retrieve the associated values:
var myObj = {
' B ': ' ASDSADFD ',
' C ': ' Masdasaf ',
' A ': ' Dsfdsfsdf '
},
Keys = [],
K, I, Len;
var newobj={};
For (k in myObj) {
if (Myobj.hasownproperty (k)) {
Keys.push (k);
}
}
Keys.sort ();
len = keys.length;
for (i = 0; i < len; i++) {
k = Keys[i];
NEWOBJ[K]=MYOBJ[K];
}
console.log( myObj );
console.log(newObj);
Alternative implementations used by method two Object.keys
:
var myObj = { ‘b‘: ‘asdsadfd‘, ‘c‘: ‘masdasaf‘, ‘a‘: ‘dsfdsfsdf‘ }, keys = Object.keys(myObj), i, len = keys.length;keys.sort();for (i = 0; i < len; i++) { k = keys[i]; newObj[k]=myObj[k];}
console.log(
keys
);
console.log( myObj );
console.log(newObj);
Sort JavaScript objects by key