排序复杂的JSON对象

时间:2010-01-18 12:17:50

标签: javascript jquery json

参考前面有关引用JSON(javascript)数组的元素和排序的问题。看到 refer to an element of JSON (Javascript) object Sorting an array of JavaScript objects

是否可以对更复杂的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);  
});

4 个答案:

答案 0 :(得分:5)

标准Array.sort采用比较器功能。使用:

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

答案 1 :(得分:1)

在您发布链接的问题中,答案或多或少是:

Sorting an array of JavaScript objects

homes.Listings.sort(function (a, b)
{
    return a.price - b.price;
});

答案 2 :(得分:0)

我建议使用工具包,例如jQuery。见Sorting JSON by values

答案 3 :(得分: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); 
});