Home > Web Front-end > JS Tutorial > body text

How to sort json data

php中世界最好的语言
Release: 2018-04-28 11:26:18
Original
2248 people have browsed it

This time I will show you how to sort json data with sort. What are the precautions for sorting json data? The following is a practical case, let's take a look.

How to sort the json data returned from the background according to a certain item in the data.

First look at the json data before sorting:

{
  "result":[
    {
      "cid":1,
      "name":"aaa",
      "price":1000
    },{
      "cid":2,
      "name":"bbb",
      "price":150
    },{
      "cid":3,
      "name":"ccc",
      "price":200
    },{
      "cid":4,
      "name":"ddd",
      "price":1500
    },{
      "cid":5,
      "name":"eee",
      "price":1100
    }
  ],
  "totalCount":5
}
Copy after login
Next, sort according to the price in json and print it to the console:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      //利用jquery中的get方法获取json数据
      $.get("exp.json","",function(data){
        var newdata=data.result
        //根据价格(price)排序
        function sortprice(a,b){
          return a.price-b.price
        }
        //利用js中的sort方法
        newdata.sort(sortprice);
        //打印排序后的数据到控制台
        console.log(newdata);
      })
    </script>
  </body>
</html>
Copy after login
This is completed according to To sort json data by price, check the sorting results in the console as follows:

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites. related articles!

Recommended reading:

VUE extends ElTableColumn

Detailed explanation of the use of watch method in Vue

The above is the detailed content of How to sort json data. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template