我的JSON如下所示。在总结之后,我找到了对numberOfPoint进行排序的方法。
{ "data": [
{
"id": {
"year": 2015,
"Name": "A"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2014,
"Name": "C"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2014,
"Name": "B"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2014,
"Name": "B"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2013,
"Name": "C"
},
"numberOfPoint": 2
}]
}
obj是我的JSON。
var result = {};
obj.data.forEach(function (a) { result[a["id"]["Name"]] = (result[a["id"]["Name"]] || 0) + a["numberOfPoint"]; });
结果如下所示
{
"A": 2,
"C": 4,
"B": 4
}
如何从最大到最小的数字点对此进行排序? 我想要这样的结果。
{
"B": 4,
"C": 4,
"A": 2
}
提前谢谢你。
答案 0 :(得分:1)
也许这会有所帮助。
obj.data.sort(function(a, b) {
return a.id.Name < b.id.Name;
});
for(var i in obj.data) {
console.log(obj.data[i].id.Name);
}
答案 1 :(得分:1)
您可以执行以下操作:
var result={
"A": 2,
"C": 4,
"B": 4,
"D": 3
}
var temp = [];
$.each(result, function(key, value) {
temp.push({v:value, k: key});
});
temp.sort(function(a,b){
if(a.v < b.v){ return 1}
if(a.v > b.v){ return -1}
return 0;
});
$.each(temp, function(index, obj) {
alert(obj.k + "-" + obj.v);
});
<强> Here is JSFiddle 强>
答案 2 :(得分:1)
var obj = { "data": [ { "id": { "year": 2015, "Name": "A" }, "numberOfPoint": 2 }, { "id": { "year": 2014, "Name": "C" }, "numberOfPoint": 2 }, { "id": { "year": 2014, "Name": "B" }, "numberOfPoint": 2 }, { "id": { "year": 2014, "Name": "B" }, "numberOfPoint": 2 }, { "id": { "year": 2013, "Name": "C" }, "numberOfPoint": 2 }] } var result = {}; obj.data.forEach(function (a) { result[a["id"]["Name"]] = (result[a["id"]["Name"]] || 0) + a["numberOfPoint"]; }); var temp = []; $.each(result, function(key, value) { temp.push({v:value, k: key}); }); temp.sort(function(a,b){ if(a.v < b.v){ return 1} if(a.v > b.v){ return -1} return 0; }); $.each(temp, function(index, obj) { alert(obj.k + "-" + obj.v); });
我希望你喜欢这个..如果你喜欢那就不要忘记投票给我......并感谢@Butani Vijay的好评。我已经共同实施了......