2009-02-05 42 views
8

我有一个jQuery json请求,并且在那个json数据中,我希望能够通过唯一值进行排序。所以我有如何从jquery中获取不同的值jquery

 
{"people":[{"pbid":"626","birthDate":"1976-02-06","name":'name'},{"pbid":"648","birthDate":"1987-05-22","name":'name'},..... 

所以,到目前为止,我有这个

 
function(data){ 
      $.each(data.people, function(i, person){ 
       alert(person.birthDate); 

} 

,但是,我在一个总损失为如何有效地只得到独特的生日,并逐年对其进行排序(或任何按其他任何个人数据排序)。

我试图做到这一点,并保持高效(我希望这是可能的)。

感谢

+0

我看到这一切的时候。而不是使用功能(我,人)警报(person.birthDate)使用功能()警报(this.birthDate) – bendewey 2009-02-05 19:38:54

回答

9

我不知道怎么高性能,这将是,但基本上我使用一个对象作为键/值字典。我没有测试过这个,但是应该在循环中对它进行排序。

function(data) { 
    var birthDates = {}; 
    var param = "birthDate" 
    $.each(data.people, function() { 
     if (!birthDates[this[param]]) 
      birthDates[this[param]] = []; 
     birthDates[this[param]].push(this); 
    }); 

    for(var d in birthDates) { 
     // add d to array here 
     // or do something with d 
     // birthDates[d] is the array of people 
    } 
} 
+0

哇,这真棒,并得到我最多(或很多)的方式,但我仍然坚持一旦我有一个数组中的唯一身份,我如何使用该查询人名? 我基本上试图说 得到的名字where birthDate = d? – pedalpete 2009-02-05 19:59:37

6
function(data){ 
    var arr = new Array(); 
    $.each(data.people, function(i, person){ 
     if (jQuery.inArray(person.birthDate, arr) === -1) { 
      alert(person.birthDate); 
      arr.push(person.birthDate); 
     } 
    }); 
} 
3

这是我的看法:

function getUniqueBirthdays(data){ 
    var birthdays = []; 
    $.each(data.people, function(){ 
     if ($.inArray(this.birthDate,birthdays) === -1) { 
      birthdays.push(this.birthDate); 
     } 
    }); 
    return birthdays.sort(); 
}