我在 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/