[英]how to get distinct values from json in jquery
我有一個 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);
})
}
但是,我完全不知道如何有效地只獲取唯一的生日,並按年份對它們進行排序(或按任何其他個人數據排序)。
我正在努力做到這一點,並對此保持高效(我希望這是可能的)。
謝謝
我不確定它的性能如何,但基本上我使用一個對象作為鍵/值字典。 我還沒有測試過這個,但這應該在循環中排序。
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
}
}
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);
}
});
}
這是我的看法:
function getUniqueBirthdays(data){
var birthdays = [];
$.each(data.people, function(){
if ($.inArray(this.birthDate,birthdays) === -1) {
birthdays.push(this.birthDate);
}
});
return birthdays.sort();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.