2010-07-12 54 views
9

我有一個JSON對象,我想先按一個鍵排序,然後按第二個鍵排序,類似於按SQL中的兩列排序。以下是我將擁有的JSON示例:如何通過兩個鍵訂購JSON對象?

{ 
    "GROUPID":3169675, 
    "LASTNAME":"Chantry" 
} 

我想按GROUPID和LASTNAME排序所有結果。我使用JSON排序功能來排序一個鍵,但不是多個。

任何幫助將是偉大的。

+1

你的例子是用於對象的屬性的散列。根據定義,這些不是排序的。我假設你有一個你想排序的這些對象的數組? – 2010-07-12 16:05:52

+0

它是一個JSON對象的數組嗎? – Castrohenge 2010-07-12 16:10:34

回答

9

假設你已經對象的數組:

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部分。它提供了一些可以擴展到多列的可定製方法。

+0

爲什麼不比較一組鍵?它使這種排序更通用,或者我錯過了什麼?請參閱下面的回覆。 – Mic 2010-07-12 17:44:19

+0

@Mic - 這正是我在鏈接答案中所做的。我不想重寫整個事情,所以只是添加了一個鏈接。 – Anurag 2010-07-12 18:02:56

36

這裏是排序對象數組一個通用的方法,用多列:

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陣列比較它們轉換在用逗號分隔的字符串。

+4

我希望我可以給你一個baggillion upvotes .. – Alex 2011-05-11 00:55:52

+1

一個這個答案就夠了;)很高興看到它幫助你! – Mic 2011-05-11 09:41:32

+0

問題爲什麼數組? 爲什麼不'(a.name - b.name) \t || (a.id - b.id)' 你可以去像: '(a.name - b.name) \t || (a.id - b.id)|| (a.idd - b.idd)' – 2013-06-21 15:57:24