我有一個JSON對象,我想先按一個鍵排序,然後按第二個鍵排序,類似於按SQL中的兩列排序。以下是我將擁有的JSON示例:如何通過兩個鍵訂購JSON對象?
{
"GROUPID":3169675,
"LASTNAME":"Chantry"
}
我想按GROUPID和LASTNAME排序所有結果。我使用JSON排序功能來排序一個鍵,但不是多個。
任何幫助將是偉大的。
我有一個JSON對象,我想先按一個鍵排序,然後按第二個鍵排序,類似於按SQL中的兩列排序。以下是我將擁有的JSON示例:如何通過兩個鍵訂購JSON對象?
{
"GROUPID":3169675,
"LASTNAME":"Chantry"
}
我想按GROUPID和LASTNAME排序所有結果。我使用JSON排序功能來排序一個鍵,但不是多個。
任何幫助將是偉大的。
假設你已經對象的數組:
var data = [
{ "GROUPID":3169675, "LASTNAME":"Chantry" },
{ "GROUPID":3169612, "LASTNAME":"Doe" },
...
];
您可以使用自定義的比較來進行排序。爲了通過GROUPID
第一排序,然後通過LASTNAME
,比較兩個對象的邏輯將是:
if GROUPID of first is smaller than second
return -1;
else if GROUPID of first is larger than second
return 1;
else if LASTNAME of first is smaller than second
return -1;
else if LASTNAME of first is larger than second
return 1;
else
return 0;
要排序的對象陣列,使用上面的算法,並調用陣列上的排序方法。排序完成後,data
應具有所需排序順序的元素。
data.sort(function(a, b) {
// compare a and b here using the above algorithm
});
這是另一個很similar question我最近回答。這是關於使用jQuery對多個列進行排序,但是您可以輕鬆地去除jQuery部分。它提供了一些可以擴展到多列的可定製方法。
這裏是排序對象數組一個通用的方法,用多列:
var arr = [
{ id:5, name:"Name3" },
{ id:4, name:"Name1" },
{ id:6, name:"Name2" },
{ id:3, name:"Name2" }
],
// generic comparison function
cmp = function(x, y){
return x > y ? 1 : x < y ? -1 : 0;
};
//sort name ascending then id descending
arr.sort(function(a, b){
//note the minus before -cmp, for descending order
return cmp(
[cmp(a.name, b.name), -cmp(a.id, b.id)],
[cmp(b.name, a.name), -cmp(b.id, a.id)]
);
});
要添加其他列進行排序,可以在陣列相比,添加其它項目。
arr.sort(function(a, b){
return cmp(
[cmp(a.name, b.name), -cmp(a.id, b.id), cmp(a.other, b.other), ...],
[cmp(b.name, a.name), -cmp(b.id, a.id), cmp(b.other, a.other), ...]
);
});
EDIT:每下面@PhilipZ評論,在JS陣列比較它們轉換在用逗號分隔的字符串。
你的例子是用於對象的屬性的散列。根據定義,這些不是排序的。我假設你有一個你想排序的這些對象的數組? – 2010-07-12 16:05:52
它是一個JSON對象的數組嗎? – Castrohenge 2010-07-12 16:10:34