2010-01-18 75 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