jQuery 对 JSON 对象进行排序

3

我在使用jQuery填充一个jQuery网格时,有以下JSON对象。

现在我需要按“performanceName”进行排序。

请指导我如何实现此操作。我知道类似的问题已经被发布100次,但我仍然在努力将排序应用到下面的JSON中。

{
    "callback": "",
    "html": "",
    "message": [
        ""
    ],
    "responseData": [
        {
            "collectionTitleId": 1107861,
            "collectionTitleIdSpecified": true,
            "performanceField": {
                "addedDate": "6/16/2011 11:11:10 PM",
                "artist": "Corbis",
                "performanceName": "Showcase Graphic 003 - Anime Girl Purple",
                "performanceType": "Graphic",
                "provider": "DMSP Dynamic Digital"
            },
            "sortOrder": "01"
        },
        {
            "collectionTitleId": 1113513,
            "collectionTitleIdSpecified": true,
            "performanceField": {
                "addedDate": "5/25/2011 9:27:39 AM",
                "artist": "Beloved",
                "performanceName": "Hating On Your Feet (Verse)",
                "performanceType": "LabelTone",
                "provider": "p1"
            },
            "sortOrder": "02"
        }
    ],
    "status": [
        "Success"
    ]
}

感谢您的提前帮助。
2个回答

10

你可以使用 Array.prototype.sort 对数组进行原地排序。默认情况下,它尝试按字母顺序排序元素,但你可以传入一个比较函数来代替。这个函数接收两个参数,并应该返回小于0、0或大于0的值来定义第1个参数在关系上应该位于第2个参数之前还是之后。

你的排序函数应该像这样:

data.responseData.sort(function (a, b) {
    a = a.performanceField.performanceName,
    b = b.performanceField.performanceName;

    return a.localeCompare(b);
});

演示链接: http://jsfiddle.net/AndyE/aC5z4/

localeCompare 方法为我们完成了比较字符串的繁重工作。


也不要忘记将排序后的值重新赋回原始值。 - sathis
@sathis:JavaScript 的 sort 是一种原地排序,因此不需要进行赋值。 - Andy E
我喜欢使用localeCompare!很棒! - Ben_Coding

0

var people = [
    { 'myKey': 'Ankit', 'status': 0 },    
    { 'myKey': 'Bhavik', 'status': 3 },
    { 'myKey': 'Parth', 'status': 7 },
    { 'myKey': 'Amin', 'status': 9 },
    { 'myKey': 'Russ', 'status': 9 },
    { 'myKey': 'Pete', 'status': 10 },
    { 'myKey': 'Ravi', 'status': 2 },
    { 'myKey': 'Tejas', 'status': 2 },
    { 'myKey': 'Dilip', 'status': 1 },
    { 'myKey': 'Piyush', 'status': 12 }
];
alert("0. At start: " + JSON.stringify(people));

//META.fn: sortData
jQuery.fn.sortData = function (prop, asc) {
        return this.sort(function (a, b) {           
            var x = a[prop];
        var y = b[prop];
            var retrunStatus = ((x < y) ? 1 : ((x > y) ? -1 : 0));
            return (asc==undefined || asc) ? (retrunStatus * -1) : retrunStatus ;        
        });
    }

people2 = $(people).sortData('myKey',false);
alert("1. After sorting (0 to x): " + JSON.stringify(people2));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接