js中json对象数组按对象属性排序---1

转载:https://www.cnblogs.com/jasonwang2y60/p/6656103.html

在实际工作经常会出现这样一个问题:后台返回一个数组中有i个json数据,需要我们根据json中某一项进行数组的排序。

例如返回的数据结构大概是这样:

   {
    result:[
      {id:1,name:'中国银行'},
      {id:3,name:'北京银行'},
      {id:2,name:'河北银行'},
      {id:10,name:'保定银行'},
      {id:7,name:'涞水银行'}
    ]
   } 

现在我们根据业务需要,要根据id的大小进行排序,按照id小的json到id大的json顺序重新排列数组的顺序

在js中添加排序的方法:

这里使用JavaScript sort() 方法,首先解释下这个sort的方法

语法:arrayObject.sort(sortby)            sortby:可选,规定排序顺序。必须是函数。

如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。要实现这一点,首先应把数组的元素都转换成字符串(如有必要),以便进行比较。

如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:

  • 若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
  • 若 a 等于 b,则返回 0。
  • 若 a 大于 b,则返回一个大于 0 的值。

下面开始使用sort(sortby) 来进行这个排序,并打印到控制台:

    function sortId(a,b){  
       return a.id-b.id  
    }
    result.sort(sortId);
    console.log(result); 

然后查看控制台,排序成功:

js中json对象数组按对象属性排序---1

附: 前端机试题一个(对数据进行排序)

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body, html {
            padding: 0;
            margin: 0;
            font-size: 14px;
            color: #000000;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            table-layout: fixed;
        }

        thead {
            background: #3d444c;
            color: #ffffff;
        }

        td, th {
            border: 1px solid #e1e1e1;
            padding: 0;
            height: 30px;
            line-height: 30px;
            text-align: center;
        }

        .sort-asc::after,
        .sort-desc::after {
            content: ' ';
            display: inline-block;
            margin-left: 5px;
            vertical-align: middle;

        }
        .sort-asc::after {
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-bottom: 4px solid #eee;
        }
        .sort-desc::after {
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-top: 4px solid #eee;
        }
    </style>
</head>
<body>
<table>
    <thead id="jsHeader">
    <tr>
        <th>product</th>
        <th>price</th>
        <th>sales</th>
    </tr>
    </thead>
    <tbody id="jsList">
    <tr>
        <td>1</td>
        <td>10.0</td>
        <td>800</td>
    </tr>
    <tr>
        <td>2</td>
        <td>30.0</td>
        <td>300</td>
    </tr>
    <tr>
        <td>3</td>
        <td>20.5</td>
        <td>100</td>
    </tr>
    <tr>
        <td>4</td>
        <td>40.5</td>
        <td>200</td>
    </tr>
    <tr>
        <td>5</td>
        <td>60.5</td>
        <td>600</td>
    </tr>
    <tr>
        <td>6</td>
        <td>50.0</td>
        <td>400</td>
    </tr>
    <tr>
        <td>7</td>
        <td>70.0</td>
        <td>700</td>
    </tr>
    <tr>
        <td>8</td>
        <td>80.5</td>
        <td>500</td>
    </tr>
    </tbody>
</table>
<script type="text/javascript">
    /**
     *  请完成 sortData 函数,根据参数的要求对表格所有行进行重新排序。
     *  1、type为product、price或者sales,分别对应第1 ~ 3列
     *  2、order为asc或者desc,asc表示升序,desc为降序
     *  3、例如 sortData('price', 'asc') 表示按照price列从低到高排序
     *  4、所有表格内容均为数字,每一列数字均不会重复
     *  5、不要使用第三方插件
     */
    function sortData(type, order) {
        //完成您的代码

        if(order == 'asc'){
            data.sort( (a, b)=> a[type] - b[type] );
        }else if(order == 'desc'){

            data.sort( (a, b)=> b[type] - a[type] );
        }

        //调用渲染视图
        render(data);
        
    }

    //渲染视图

    function render(data) {
        let tbodyHTML = '';
        for( let i = 0; i < data.length; i++ ){
            tbodyHTML += ` <tr>
                                <td>${data[i].product}</td>
                                <td>${data[i].price}</td>
                                <td>${data[i].sales}</td>
                            </tr>`
        }

        document.getElementById('jsList').innerHTML = tbodyHTML;
    }



    //获取数据
    let oTbody = document.getElementById('jsList');
    let oTr = oTbody.getElementsByTagName('tr');

    let data = [];

    for(let i = 0; i < oTr.length; i++){
        data[i] = {
            product: oTr[i].getElementsByTagName('td')[0].innerText,
            price: oTr[i].getElementsByTagName('td')[1].innerText,
            sales: oTr[i].getElementsByTagName('td')[2].innerText,
        }
    }


    /* 原数据格式
       [
    *   {product: "1", price: "10.0", sales: "800"},
    *   {product: "2", price: "30.0", sales: "300"},
    *   {product: "3", price: "20.5", sales: "100"},
    *   {product: "4", price: "40.5", sales: "200"},
    *   {product: "5", price: "60.5", sales: "600"},
    *   {product: "6", price: "50.0", sales: "400"},
    *   {product: "7", price: "70.0", sales: "700"},
    *   {product: "8", price: "80.5", sales: "500"}
    *  ]
    * */



    //sortData('product', 'desc');
    //调用排序函数
    sortData('price','desc')




    //sortData('product', 'desc');

</script>
</body>
</html>
View Code

例如返回的数据结构大概是这样:

   {
    result:[
      {id:1,name:'中国银行'},
      {id:3,name:'北京银行'},
      {id:2,name:'河北银行'},
      {id:10,name:'保定银行'},
      {id:7,name:'涞水银行'}
    ]
   } 

现在我们根据业务需要,要根据id的大小进行排序,按照id小的json到id大的json顺序重新排列数组的顺序

在js中添加排序的方法:

这里使用JavaScript sort() 方法,首先解释下这个sort的方法

语法:arrayObject.sort(sortby)            sortby:可选,规定排序顺序。必须是函数。

如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。要实现这一点,首先应把数组的元素都转换成字符串(如有必要),以便进行比较。

如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:

  • 若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
  • 若 a 等于 b,则返回 0。
  • 若 a 大于 b,则返回一个大于 0 的值。

下面开始使用sort(sortby) 来进行这个排序,并打印到控制台:

    function sortId(a,b){  
       return a.id-b.id  
    }
    result.sort(sortId);
    console.log(result); 

然后查看控制台,排序成功:

js中json对象数组按对象属性排序---1

附: 前端机试题一个(对数据进行排序)

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body, html {
            padding: 0;
            margin: 0;
            font-size: 14px;
            color: #000000;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            table-layout: fixed;
        }

        thead {
            background: #3d444c;
            color: #ffffff;
        }

        td, th {
            border: 1px solid #e1e1e1;
            padding: 0;
            height: 30px;
            line-height: 30px;
            text-align: center;
        }

        .sort-asc::after,
        .sort-desc::after {
            content: ' ';
            display: inline-block;
            margin-left: 5px;
            vertical-align: middle;

        }
        .sort-asc::after {
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-bottom: 4px solid #eee;
        }
        .sort-desc::after {
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-top: 4px solid #eee;
        }
    </style>
</head>
<body>
<table>
    <thead id="jsHeader">
    <tr>
        <th>product</th>
        <th>price</th>
        <th>sales</th>
    </tr>
    </thead>
    <tbody id="jsList">
    <tr>
        <td>1</td>
        <td>10.0</td>
        <td>800</td>
    </tr>
    <tr>
        <td>2</td>
        <td>30.0</td>
        <td>300</td>
    </tr>
    <tr>
        <td>3</td>
        <td>20.5</td>
        <td>100</td>
    </tr>
    <tr>
        <td>4</td>
        <td>40.5</td>
        <td>200</td>
    </tr>
    <tr>
        <td>5</td>
        <td>60.5</td>
        <td>600</td>
    </tr>
    <tr>
        <td>6</td>
        <td>50.0</td>
        <td>400</td>
    </tr>
    <tr>
        <td>7</td>
        <td>70.0</td>
        <td>700</td>
    </tr>
    <tr>
        <td>8</td>
        <td>80.5</td>
        <td>500</td>
    </tr>
    </tbody>
</table>
<script type="text/javascript">
    /**
     *  请完成 sortData 函数,根据参数的要求对表格所有行进行重新排序。
     *  1、type为product、price或者sales,分别对应第1 ~ 3列
     *  2、order为asc或者desc,asc表示升序,desc为降序
     *  3、例如 sortData('price', 'asc') 表示按照price列从低到高排序
     *  4、所有表格内容均为数字,每一列数字均不会重复
     *  5、不要使用第三方插件
     */
    function sortData(type, order) {
        //完成您的代码

        if(order == 'asc'){
            data.sort( (a, b)=> a[type] - b[type] );
        }else if(order == 'desc'){

            data.sort( (a, b)=> b[type] - a[type] );
        }

        //调用渲染视图
        render(data);
        
    }

    //渲染视图

    function render(data) {
        let tbodyHTML = '';
        for( let i = 0; i < data.length; i++ ){
            tbodyHTML += ` <tr>
                                <td>${data[i].product}</td>
                                <td>${data[i].price}</td>
                                <td>${data[i].sales}</td>
                            </tr>`
        }

        document.getElementById('jsList').innerHTML = tbodyHTML;
    }



    //获取数据
    let oTbody = document.getElementById('jsList');
    let oTr = oTbody.getElementsByTagName('tr');

    let data = [];

    for(let i = 0; i < oTr.length; i++){
        data[i] = {
            product: oTr[i].getElementsByTagName('td')[0].innerText,
            price: oTr[i].getElementsByTagName('td')[1].innerText,
            sales: oTr[i].getElementsByTagName('td')[2].innerText,
        }
    }


    /* 原数据格式
       [
    *   {product: "1", price: "10.0", sales: "800"},
    *   {product: "2", price: "30.0", sales: "300"},
    *   {product: "3", price: "20.5", sales: "100"},
    *   {product: "4", price: "40.5", sales: "200"},
    *   {product: "5", price: "60.5", sales: "600"},
    *   {product: "6", price: "50.0", sales: "400"},
    *   {product: "7", price: "70.0", sales: "700"},
    *   {product: "8", price: "80.5", sales: "500"}
    *  ]
    * */



    //sortData('product', 'desc');
    //调用排序函数
    sortData('price','desc')




    //sortData('product', 'desc');

</script>
</body>
</html>
View Code