jquery排序json对象

标签 jquery json sorting

我在 jquery 中有下面的 Json 对象,我用它来填充 jquery 网格。

现在我需要根据“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"
    ]
}

提前致谢

最佳答案

您可以使用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);
});

Working demo: http://jsfiddle.net/AndyE/aC5z4/

localeCompare 为我们完成了比较字符串的艰苦工作。

关于jquery排序json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7834529/

相关文章:

jquery - 使用 jquery 获取自定义标签(包含冒号)值

function - jQuery 函数重复

json - Flutter 快照数据为空

javascript - 如何使用 jquery 根据 id 属性对列表项进行排序?

javascript - 如何隐藏 optgroup/option 元素?

java - 在 java Rest API 中使用 json POST 请求的问题

javascript - getJSON 不显示文件路径

algorithm - Bubblesort 优于其他排序算法?

linux - 如何在 Linux 中随机化文本文件的列

javascript - 如何转换 HH :mm:ss string to a JavaScript Date object?