JavaScript sorts JSON-formatted data

Source: Internet
Author: User

JavaScript is a weakly typed language, and the system iterates through the JSON data to sort by its own data type, as follows:

The code is as follows Copy Code

<script Src= "Jquery.js" ></script>
<script>
var json1 = {
         "2": {"name": "1th"},
        "1": {"name": "2nd"},
         "3": {"name": "3rd"}
       }
var json2 = {
        "2_str": {"name": "1th www.111cn.net"},
         "1_str": {"name": "2nd"},
        "3_str": {"name": "3rd"}       
}
$.each (Json1, function (i,item) {
         alert (i+ ":" +item.name);
});
 
$.each (json2, function (i,item) {
        alert (i+ ":" + Item.name);
});
</script>


How to sort JSON data by a specified sort:

The code is as follows Copy Code

<script src= "Jquery.js" ></script>
<script type= "Text/javascript" >
var json = {"Languages": [
{"id": "1", "name": "PHP", "Sort": "1"},
{"id": "2", "Name": "Jacscript", "Sort": "3"},
{"id": "3", "Name": "PYTHON", "Sort": "4"},
{"id": "4", "Name": "NODE." JS ", sort": "2"}
]};

Sort before www.111cn.net
$.each (json.languages, function (i) {
Alert (json.languages[i].id+ "" +json.languages[i].name+ "Sort:" +json.languages[i].sort);
});

To sort
json["Languages"].sort (function (a,b) {
return a["Sort"] > b["Sort"]? 1: (a["sort"] = = b["Sort"]? 0:-1);
});

After sorting
$.each (json.languages, function (i) {
Alert (json.languages[i].id+ "" +json.languages[i].name+ "Sort:" +json.languages[i].sort);
});
</script>

The


primarily uses the sort method of JavaScript to sort the data in the specified way.

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.