简体   繁体   English

如何根据jQuery中单击的选项对JSON对象进行排序?

[英]How to sort JSON object based on option clicked in jquery?

Below is my ajax: This will display result from a query from PHP page that filtered by category , postcode and rate keyed in by user. 下面是我的ajax:这将显示来自PHP页面的查询结果,该查询按用户键入的categorypostcoderate过滤。

$("form").on("submit", function () {
    var data = {
        "action": "test"
    };

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax2.php",
        data: data,
        success: function (data) {

        $("#main_content").slideUp("normal",function(){
         for (i = 0; i < data.length; i++) {

$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");


            //alert(data[i].name) 
        }

            });
        }


    });
    return false;


});

I wish to know how to control this part, I mean how to control which action to take after success: 我想知道如何控制这部分,我的意思是如何控制成功后要采取的行动:

By default it can show as below: But when 'Sort by rate' clicked it should sort by rate and display inside .the-return . 默认情况下,它可以显示如下:但是单击“按比率排序”时,应按比率排序并显示在.the-return And when 'sort by rank' clicked it should sort by rank and display. 当单击“按等级排序”时,应按等级排序并显示。 How can I locate the switch statement in here and display accordingly please? 如何在此处找到switch语句并相应显示? I'm worn out looking for an answer to this, any help would be greatly appreciated! 我已经筋疲力尽了,无法寻求答案,我们将不胜感激! Thanks in advance!!!! 提前致谢!!!!

success: function (data) {

            $("#main_content").slideUp("normal",function(){
             for (i = 0; i < data.length; i++) {

    $(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");

            }

        });
       }        



    });
   return false;

  });

Json object can be sorted this way: 可以通过以下方式对Json对象进行排序:

data.sort(function (a, b) {
    var retVal = 0;
    switch (sortOption) {
        case 1:
            retVal = a.property > b.property ? 1 : (a.property < b.property ? -1 : 0);
            break;
        ....
    }
    return retVal;
});

Explaination: The data here is a json object. 说明:这里的data是一个json对象。 The sort() is a javascript function. sort()是一个javascript函数。 This function is called for each pair of json objects in the json array. 对于json数组中的每对json对象,都会调用此函数。 The returned value ( retVal here) is used by js to decide if the json element a precedes json element b . js使用返回的值(此处为retVal )来确定json元素a在json元素b之前。 If the retVal value is 1, b precedes a , vice-versa for -1 and undecided for 0. sortOption is for your requirement. 如果retVal值为1, b前面a ,反之亦然为-1和犹豫不决的0 sortOption是您的要求。 You can use it to decide on what to compare the elements, depending on the Sort by value selected by the user. 您可以使用它来决定要比较哪些元素,具体取决于用户选择的“ Sort bySort by值。
You can place this code at the place where you want to sort the json array. 您可以将此代码放在要对json数组进行排序的位置。

Code for you: 代码为您:

success: function (data) {
    data.sort(function (a, b) {
        var retVal = 0;
        switch (sortOption) {
            case 1:
                retVal = a.property > b.property ? 1 : (a.property < b.property ? -1 : 0);
                break;
                // .... many cases here
        }
        return retVal;
    });
    $("#main_content").slideUp("normal", function () {
        for (i = 0; i < data.length; i++) {

            $(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode + "<br/>Reputation:" + data[i].reputation + "<br/>Review Plus:" + data[i].plus + "<br/>Review Negative:" + data[i].neg + "<br/><h1>Availability</h1>Week Morning:" + data[i].weekM + "<br/>Week Afternoon:" + data[i].weekA + "<br/>Week Evening:" + data[i].weekE + "<br/>Weekend Morning:" + data[i].endM + "<br/>Weekend Afternoon:" + data[i].endA + "<br/>Week Evening:" + data[i].endE + "</div>");

        }

    });
}

Call sortByProperty , pass it the property name, the array to sort, and a bool signifying whether to sort descending or not. 调用sortByProperty ,将属性名称,要排序的数组以及表示是否按降序排序的布尔值传递给它。

var currentlySortingBy = '';
var sortDesc = true;

var sortByProperty = function (propertyName, array, sortDescending) {
    currentlySortingBy = propertyName;
    sortDesc = sortDescending;

    return array.slice(0).sort(propertyComparer);
};

var propertyComparer = function (a, b) {
    var isString = typeof a[currentlySortingBy] === 'string';

    var aProp = isString ? a[currentlySortingBy].toLowerCase() : a[currentlySortingBy];
    var bProp = isString ? b[currentlySortingBy].toLowerCase() : b[currentlySortingBy];

    var sortDir = sortDesc ? 1 : -1;
    return ((aProp < bProp) ? sortDir : ((aProp > bProp) ? -sortDir : 0));
};

There actually are multiple ways of sorting JSON objects. 实际上,有多种方式对JSON对象进行排序。 The first way is to write your own order function. 第一种方法是编写自己的订单函数。

var sort_by = function(field, reverse, primer){

   var key = primer ? 
       function(x) {return primer(x[field])} : 
       function(x) {return x[field]};

   reverse = !reverse ? 1 : -1;

   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     } 
}

// Sort by price high to low
myJson.sort(sort_by('price', true, parseInt));

// Sort by city, case-insensitive, A-Z
myJson.sort(sort_by('city', false, function(a){return a.toUpperCase()}));

Obtained from: https://stackoverflow.com/a/979325/2076351 获取自: https : //stackoverflow.com/a/979325/2076351

Another option would be to use underscorejs. 另一种选择是使用underscorejs。

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');
=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];

As displayed here: http://underscorejs.org/#sortBy 如此处所示: http : //underscorejs.org/#sortBy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM