JS arranges objects in alphabetical order by attribute name

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.