2010-01-18 73 views
0

參考有關引用JSON(javascript)數組的元素和排序的早期問題。見 refer to an element of JSON (Javascript) object Sorting an array of JavaScript objects排序複雜的JSON對象

是否有可能進行排序的更復雜的JavaScript陣列的一個分支,如在下面的例子中通過價格排序?

var homes = 
{ 
    "Agents" : [ 
     { 
      "name" : "Bob Barker" 
     }, 
     { 
      "name" : "Mona Mayflower" 
     } 
    ] , 
    "Listings" : [ 
     { 
      "h_id": "3", 
      "city": "Dallas", 
      "state": "TX", 
      "zip": "75201", 
      "price": "162500" 
     }, 
     { 
      "h_id": "4", 
      "city": "Bevery Hills", 
      "state": "CA", 
      "zip": "90210", 
      "price": "319250" 
     }, 
     { 
      "h_id": "5", 
      "city": "New York", 
      "state": "NY", 
      "zip": "00010", 
      "price": "962500" 
     } 
    ] 
} 

謝謝大家的幫助!!!

編輯

很抱歉的混亂。我的意思是JavaScript作爲標籤。 (這應該是顯而易見的其餘問題)我得到了排序工作,只是無法遍歷數組。

// before sort 
alert(homes.Listings[0].price); 
// sort 
homes.Listings.sort(sort_by('price', false, parseInt)); 
// after sort works: 
alert(homes.Listings[0].price); 
// iteration does not work "$ is not defined" 
$.each(homes.Listings, function(i, thisHome) { 
    alert(thisHome.price); 
}); 
+0

@BalusC,這就是我想知道的,以及爲什麼我擔心發佈我的答案。 – 2010-01-18 12:29:48

+0

http://en.wikipedia.org/wiki/Schwartzian_transform – 2010-01-18 12:36:31

回答

5

標準Array.sort採用比較功能。使用:

function makeNumericCmp(property) { 
    return function (a, b) { 
     return parseInt(a[property]) - parseInt(b[property]); 
    }; 
} 
homes.Listings.sort(makeNumericCmp('price')); 
0

我會建議使用的工具包,例如jQuery的。請參閱Sorting JSON by values

+0

爲什麼選擇投票?解釋你的投票似乎是一個體面的事情。 – Martin 2010-01-18 13:11:33

+0

我沒有投票給你,但我建議你推薦一個小錘子的小問題。 – Upperstage 2010-01-18 14:22:45

+0

你說得對,我不知道「標準的Array.sort需要一個比較函數。」 – Martin 2010-01-18 14:52:31

0

對不起,我感到困惑。我的意思是JavaScript作爲標籤。 (這應該是顯而易見的其餘問題) 我得到了排序工作,只是無法遍歷數組遍歷 。

// before sort 
alert(homes.Listings[0].price); 
// sort 
homes.Listings.sort(sort_by('price', false, parseInt)); 
// after sort works: 
alert(homes.Listings[0].price); 
// iteration does not work "$ is not defined" 
$.each(homes.Listings, function(i, thisHome) { 
    alert(thisHome.price); 
}); 
+0

如果打算作爲您的問題的答案(您可以這樣做),那麼這篇文章很好,但除此之外,您應該編輯您的問題以添加說明。 SO是一個問答網站,而不是論壇。至於錯誤,這是因爲'$'不是標準對象;它由各種庫定義,您可能沒有加載。 – outis 2010-01-18 14:37:33

+0

我已將此更新信息添加到您的問題 - 請刪除此「答案」。 – 2010-01-18 14:42:52

+0

感謝您的建議。在編輯過程中,JS庫脫離了頁面。 我甚至沒有想過檢查。 – rshid 2010-01-18 14:44:28