使用jquery获取json Data的唯一值 [英] Get Unique values for json Data using jquery
本文介绍了使用jquery获取json Data的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的json数据如下:
I have my json data as follows:
var Data = [{"Name":"a1","ID":"b1", "year":"2011"},
{"Name":"a2", "ID":"b2", "year":"2012"},
{"Name":"a3", "ID":"b3", "year":"2012"},
{"Name":"a4", "ID":"b4", "year":"2010"}];
我需要按如下方式显示数据,
I need to display the data as follows,
2012
a2 b2
a3 b3
2011
a1 b1
2010
a4 b4
这就是我的尝试:获取唯一值
This is what I have tried: To get unique values
var uniqueGroups = {};
$.each(Data, function () {
uniqueGroups[this.year] = this.year;
});
$.each(uniqueGroups, function (g) {
resultsdiv.append('<p>' + g +'</p>' );
$.each(json.Data, function (i, memDetails) {
if (memDetails.year == g) {
resultsdiv.append('<div>' + memDetails.Name + memDetails.ID +'</div>');
}
});
});
这打印出结果但按升序排列,但我要求它按降序排列。我怎么处理这个? (即使我在服务器上对json进行排序,它也按升序返回)
This prints out the results but in ascending order, But I would require it to be in descending order. How can I approach this? (Even if I sort the json on the server, it is returning in ascending order)
推荐答案
var uniqueGroups = [];
$.each(json.Data, function () {
var year = parseInt(this.year);
if (uniqueGroups.indexOf(year) < 0) {
uniqueGroups.push(year);
};
});
uniqueGroups.sort(function(x, y) { return x < y; });
$.each(uniqueGroups, function (index, year) {
resultsdiv.append('<p>' + year.toString() + '</p>');
$.each(Data, function (i, memDetails) {
if (memDetails.year == year.toString()) {
resultsdiv.append('<div>' + memDetails.Name + memDetails.ID + '</div>');
}
});
});
这篇关于使用jquery获取json Data的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文