我在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"
]
}
提前致谢
答案 0 :(得分: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);
});
localeCompare
为我们比较字符串做了很多努力。
答案 1 :(得分: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));