如何在jquery中从json获取不同的值

ped*_*ete 8 jquery json

我有一个jquery json请求,并且在json数据中我希望能够按唯一值排序.所以我有

{"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);

}

但是,我完全失去了如何有效地获得唯一的birthDates,并按年份(或任何其他个人数据)进行排序.

我正在努力做到这一点,并且有效率(我希望这是可能的).

谢谢

ben*_*wey 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
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)