var obj = {name: "Zhangsan", Age:8, Ace:5, NBME: "Lisi"};//the object to sort
function Objkeysort (obj) {//Sort
var newkey = Object.keys (obj). sort ();
Use the Keys method of the object's built-in class to get the property names of the objects to sort, and then use the Sort method on the array prototype to sort the obtained property names, Newkey is an array
var newObj = {};//Creates a new object for storing sorted key-value pairs
for (var i = 0; i < newkey.length; i++) {//Traversal Newkey array
Newobj[newkey[i]] = obj[newkey[i]];//adds the key-value pairs in sorted order to the newly created object
}
Return newobj;//returns the new ordered object
}
Objkeysort (obj); function execution
Object {ace:5, age:8, Name: "Zhangsan", Nbme: "Lisi"};//execution result
If you want to arrange in reverse order, simply invert each item in the Newkey array, that is, var newkey = Object.keys (obj). Sort (). reverse ();
Objkeysort (obj); function execution
Object {nbme: "Lisi", Name: "Zhangsan", Age:8, ace:5};//execution result
JS arranges objects in alphabetical order by attribute name